如何从Bash中读取参数

4

我想知道如何通过终端传递参数给bash脚本,并读取它们,根据参数处理脚本功能。

如果我做了这样的事情:

./scriptname.sh install
#or
./scriptname.sh assets install

如何表达,第一个参数安装某个东西,而第二个参数根据第一个参数做其他事情。


使用 $1 作为实例。您可以通过执行 if [ -z $1 ]; then echo "您未输入任何参数。" fi 来检查其是否存在。 - Engineer2021
1
http://www.gnu.org/software/bash/manual/bashref.html#Positional-Parameters 和 http://www.gnu.org/software/bash/manual/bashref.html#Special-Parameters。 - glenn jackman
2
顺便说一下,如果您在谷歌搜索“bash脚本命令行参数”或类似的关键词,肯定会得到很多结果。没别的意思,但这个问题是非常容易解决的。 - Felix Kling
3个回答

6
$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 

2
除非有特定的原因,否则始终优先选择带引号的 "$@" 而不是 $*$@ - glenn jackman
1
为了将所有变量放在一个地方:$$ 给出 shell 的进程 ID,$! 给出最近执行的后台进程的进程 ID,$? 给出上次退出状态,$_ 给出当前脚本的绝对文件名。 - Kevin

2

使用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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接