我想知道如何通过终端传递参数给bash脚本,并读取它们,根据参数处理脚本功能。
如果我做了这样的事情:
./scriptname.sh install
#or
./scriptname.sh assets install
如何表达,第一个参数安装某个东西,而第二个参数根据第一个参数做其他事情。
我想知道如何通过终端传递参数给bash脚本,并读取它们,根据参数处理脚本功能。
如果我做了这样的事情:
./scriptname.sh install
#or
./scriptname.sh assets install
如何表达,第一个参数安装某个东西,而第二个参数根据第一个参数做其他事情。
$0 is the name of the command
$1 first parameter
$2 second parameter
$3 third parameter etc. etc
$# total number of parameters
for args in $*
blah blah
"$@"
而不是 $*
或 $@
。 - glenn jackman$$
给出 shell 的进程 ID,$!
给出最近执行的后台进程的进程 ID,$?
给出上次退出状态,$_
给出当前脚本的绝对文件名。 - Kevin使用bash内置功能getopts
可以很好地将参数传递给脚本。
您可以像这样使用它:
# a script that accepts -h -a <argument> -b
while getopts "ha:b" OPTION
do
case $OPTION in
h)
# if -h, print help function and exit
helpFunction
exit 0
;;
a)
# -a requires an argument (because of ":" in the definition) so:
myScriptVariable=$OPTARG
;;
b)
# do something special
doSomeThingSpecial
;;
?)
echo "ERROR: unknonw options!! ABORT!!"
helpFunction
exit -1
;;
esac
done
$1
、$2
等来访问特定参数。例如:“在 'for file in $1/*' 中,"$1/*"的含义是什么?"。"$@"
循环遍历你的参数。例如:https://github.com/gturri/dotfiles/blob/master/bootstrap.sh#L64。
$1
作为实例。您可以通过执行if [ -z $1 ]; then echo "您未输入任何参数。" fi
来检查其是否存在。 - Engineer2021