简体   繁体   English

创建一个Shell脚本以在Linux上运行Java程序

[英]Create a shell script to run a Java program on Linux

I have created a java program which syncs the contents of two directories. 我创建了一个Java程序来同步两个目录的内容。 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. 该程序将两个目录的位置作为参数来同步它们,同步信息存储在每个目录内的JSON格式文件中。 I have one referenced library json-simple-1.1.1.jar 我有一个引用的库json-simple-1.1.1.jar

I'm running this from eclipse on windows and everything is working correctly. 我正在Windows上从eclipse运行此程序,一切正常。 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. 我想创建一个shell脚本,以便我可以在Linux终端上通过输入sync dir1 dir2来运行它,其中sync是我的Java程序,而dir1dir2是要从当前目录同步的目录的路径。

I'm very new to shell scripts and Linux and unsure whether this is easy to do or will take me all day. 我对Shell脚本和Linux还是很陌生,因此不确定这是容易做到还是会花费我一整天。

create a file named "sync" in /usr/bin containing the following: 在/ usr / bin中创建一个名为“ sync”的文件,其中包含以下内容:

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

Replace {PATH TO JARFILE} with the path to the jarfile {PATH TO JARFILE}替换为jarfile的路径

Make the file executable by typing chmod +x sync while in /usr/bin 在/ usr / bin中输入chmod +x sync使文件可执行

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. 您可以创建一个名称为“ run.sh”的shell(注意,.sh扩展名告诉它是一个shell脚本),然后将其复制到/ usr / local / bin目录中。

1.Script (run.sh) 1.脚本(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 将脚本复制到/ usr / local / bin

    cp run.sh /usr/local/bin cp run.sh / usr / local / bin

  2. Give execute permission to the script 授予脚本执行权限

    chmod u+x /usr/local/bin/test.sh 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. 现在您可以在命令行上仅输入单词run或run.sh:shell将自动完成脚本名称,也可以通过按Enter键来执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM