shell脚本命令行参数传递,linux 学习收藏!

命令行参数也称为位置参数,这些参数是运行时终端上的 shell 脚本所特有的。在命令行传递给 shell 脚本的每个变量都存储在相应的 shell 变量中,包括 shell 脚本名称。

在本教程中,我们将学习如何在 Linux 中向 bash shell 脚本传递命令行参数。

command-line-arguments

参数说明如下:

command-line-shell-variables

让我们创建一个名为 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

脚本输出如下

Pass-command-line-arguments-bash-script

在上面的脚本中,我们也可以使用 $@ 代替 $* 来获取所有参数。这两个变量之间的关键区别在于 $* 以单个字符串表示所有参数,而 $@ 以数组形式表示参数,或者 $@ 展开为多个参数。

$@ 总是优先使用,为了理解它们的区别,让我们创建以下脚本。

$ 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

执行脚本并注意其中的区别

Arguments-Example-Bash-Script

我的开源项目

酷瓜云课堂-开源知识付费解决方案

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值