bash 将多个参数传递给shell脚本并解析它们
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30560671/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 13:06:09 来源:igfitidea点击:
Passing multiple parameters to shell script and parsing them
提问by user3834663
I am trying to run the following program, I need to pass multiple options to get the command to be executed. Here for example: I am giving the inputs
我正在尝试运行以下程序,我需要传递多个选项来获取要执行的命令。例如:我正在提供输入
/test.sh -s -n
script test.sh:
脚本test.sh:
#! /bin/bash
#set -x
while [ $# -gt 0 ]
do
case in
-s) service=
shift
;;
-n) node=
command
break
;;
*) echo "Invalid Argument"
break
;;
esac
done
回答by Kusalananda
Using the getopts
built-in command in bash:
getopts
在bash 中使用内置命令:
#!/bin/bash
service="default"
node="default"
while getopts 's:n:' opt; do
case $opt in
s) service="$OPTARG" ;;
n) node="$OPTARG" ;;
*) exit 1 ;;
esac
done
echo "service = '${service}'"
echo "node = '${node}'"
Testing it:
测试它:
$ ./test.sh
service = 'default'
node = 'default'
$ ./test.sh -s hello -n world
service = 'hello'
node = 'world'
$ ./test.sh -n world -s hello
service = 'hello'
node = 'world'
$ ./test.sh -e eh
./test.sh: illegal option -- e