命令行参数也称为位置参数,这些参数是运行时终端上的 shell 脚本所特有的。在命令行传递给 shell 脚本的每个变量都存储在相应的 shell 变量中,包括 shell 脚本名称。
在本教程中,我们将学习如何在 Linux 中向 bash shell 脚本传递命令行参数。
参数说明如下:
让我们创建一个名为 arguments.sh 的 shell 脚本,它将显示所提供的命令行参数,并计算参数的数量、第一个参数的值和脚本的进程 ID (PID)。
$ vi arguments.sh
#!/bin/bash
#This Script demonstrate the usage of command line arguments in bash script
echo "There are $# arguments pass at command line"
echo "The arguments supplied are : $*"
echo "The first command line argument is: $1"
echo "The PID of the script is: $$"
使用 chmod 命令为脚本分配可执行权限
$ chmod +x arguments.sh
带参数执行脚本
$ ./arguments.sh Debian RockyLinux Ubuntu RHEL SUSE
脚本输出如下
在上面的脚本中,我们也可以使用 $@
代替 $*
来获取所有参数。这两个变量之间的关键区别在于 $*
以单个字符串表示所有参数,而 $@
以数组形式表示参数,或者 $@
展开为多个参数。
$@
总是优先使用,为了理解它们的区别,让我们创建以下脚本。
$ vi arguments-new.sh
#!/bin/bash
echo "With *:"
for arg in "$*"
do
echo "<$arg>"
done
echo
echo "With @:"
for arg in "$@"
do
echo "<$arg>"
done
执行脚本并注意其中的区别