Create a shell script to run a Java program on Lin

2019-05-01 16:27发布

问题:

I have created a java program which syncs the contents of two directories. The program takes the location of the two directories as arguments the proceeds to sync them, the sync information is them stored in a JSON formatted file inside each directory. I have one referenced library json-simple-1.1.1.jar

I'm running this from eclipse on windows and everything is working correctly. I want to create a shell script so that I can run this on a Linux terminal by typing sync dir1 dir2 where sync is my java program and dir1 and dir2 are the paths to the directories to synchronize from the current directory.

I'm very new to shell scripts and Linux and unsure whether this is easy to do or will take me all day.

回答1:

create a file named "sync" in /usr/bin containing the following:

java -jar {PATH TO JARFILE} $1 $2

Replace {PATH TO JARFILE} with the path to the jarfile

Make the file executable by typing chmod +x sync while in /usr/bin



回答2:

you can create a shell with name say "run.sh" (note .sh extension which tell it is a shell script) and copy it in /usr/local/bin directory.

1.Script (run.sh)

#!/bin/sh

arg1=$1
arg2=$2

##directory where jar file is located    
dir=/directory-path/to/jar-file/

##jar file name
jar_name=json-simple-1.1.1.jar

## Permform some validation on input arguments, one example below
if [ -z "$1" ] || [ -z "$2" ]; then
        echo "Missing arguments, exiting.."
        echo "Usage : $0 arg1 arg2"
        exit 1
fi

java -jar $dir/$jar_name arg1 arg2
  1. copy the script in /usr/local/bin

    cp run.sh /usr/local/bin

  2. Give execute permission to the script

    chmod u+x /usr/local/bin/test.sh

  3. now you can type just word run or run.sh on command line : shell will auto-complete the script name and also it can executed by pressing enter key.



标签: java linux shell