Shell脚本常用变量之$$、$0、$?、$#等

本文通过一个具体的shell脚本实例,详细解析了$$、$0、$?、$#、$*、$@、$1、$2等变量在脚本中的用法,并展示了如何调用和传递参数。在测试部分,展示了参数的实际应用,包括循环遍历参数列表。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写脚本:

[root@mysql-node1 ~]# cat vartest.sh
#!/bin/sh

bingo() {
  echo "Bingo! Below is the output of a defined function."
  echo "filelname: $0"
  echo "argument List: $@"
  echo "1st argument: $1"

  echo '############## Loop of $@ ############'
  for gee in $@
  do
    echo $gee
  done
}

echo "PID: $$"
echo `ps -ef | grep $0`
echo "filelname: $0"
echo " "

echo "returnValue of Last Shell Cmd: $?"
echo "argument List: $*"
echo "argument List: $@"
echo "number of arguments: $#"
echo "1st argument: $1"
echo "2nd argument: $2"

echo " "
bingo Apple Amazon HBO Netflix

[root@mysql-node1 ~]#

测试:

[root@mysql-node1 ~]# ./vartest.sh Arthur Morgan Freeman
PID: 1742
root 1742 1469 0 04:33 pts/0 00:00:00 /bin/sh ./vartest.sh Arthur Morgan Freeman root 1743 1742 0 04:33 pts/0 00:00:00 /bin/sh ./vartest.sh Arthur Morgan Freeman root 1745 1743 0 04:33 pts/0 00:00:00 grep ./vartest.sh
filelname: ./vartest.sh

returnValue of Last Shell Cmd: 0
argument List: Arthur Morgan Freeman
argument List: Arthur Morgan Freeman
number of arguments: 3
1st argument: Arthur
2nd argument: Morgan

Bingo! Below is the output of a defined function.
filelname: ./vartest.sh
argument List: Apple Amazon HBO Netflix
1st argument: Apple
############## Loop of $@ ############
Apple
Amazon
HBO
Netflix
[root@mysql-node1 ~]#

总结:

  • $$:当前shell脚本运行时的PID;
  • $0:当前运行shell脚本的文件名;
  • $?:上一次运行shell命令的返回值,0表示正常;
  • $#:当前运行shell脚本传入的参数个数;
  • $*:当前运行shell脚本传入的参数列表;
  • $@:当前运行shell脚本传入的参数列表;
  • $1:当前运行shell脚本传入的第一个参数;
  • $2 :当前运行shell脚本传入的第二个参数,以此类推。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

GottdesKrieges

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值