演示位置参数和特殊参数的脚本及ai解析

#!/bin/bash

echo "Hello,$USER,the output of this script are as follows:"
echo "The script name is : $(basename $0)"
echo "The first param of the script is : $1"
echo "The second param of the script is : $2"
echo "The tenth param of the script is : ${10}"
echo "All the params you input are : $@"
echo "All the params you input are : "$*""
echo "The number of the params you input are: $#"
echo "The process ID for this script is : $$"
echo "The exit status of this script is : $?"

逐帧解析

🔍 逐帧解析 mytest1.sh 执行过程

一、命令执行

[root@localhost ~]# bash mytest1.sh a b c d e f g h i j k l m

二、参数分布解析

2.1 位置参数映射

传入参数: a b c d e f g h i j k l m
索引:     1 2 3 4 5 6 7 8 9 10 11 12 13
         ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑  ↑  ↑  ↑
         $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11} ${12} ${13}

2.2 具体对应关系

参数位置变量说明
第1个$1a第一个参数
第2个$2b第二个参数
第3个$3c第三个参数
第4个$4d第四个参数
第5个$5e第五个参数
第6个$6f第六个参数
第7个$7g第七个参数
第8个$8h第八个参数
第9个$9i第九个参数
第10个${10}j第十个参数(必须用{})
第11个${11}k第十一个参数
第12个${12}l第十二个参数
第13个${13}m第十三个参数

三、脚本输出逐行解析

第1行输出

Hello,root,the output of this script are as follows:
  • $USER = root(当前登录用户)

第2行输出

The script name is                    : mytest1.sh
  • $(basename $0) = mytest1.sh(去掉路径的脚本名)

第3行输出

The first param of the script is      : a
  • $1 = a(第一个参数)

第4行输出

The second param of the script is     : b
  • $2 = b(第二个参数)

第5行输出

The tenth param of the script is      : j
  • 关键点${10} = j(第十个参数)
  • 注意是${10}不是$10$10会被解析成$1 + “0”)

第6行输出

All the params you input are          : a b c d e f g h i j k l m
  • $@ = 所有参数,空格分隔(无引号时与$*看起来一样)

第7行输出

All the params you input are          : a b c d e f g h i j k l m
  • "$*" = 所有参数合成一个字符串(但因为没空格,看起来和$@一样)

第8行输出

The number of the params you input are: 13
  • $# = 13(参数总数)

第9行输出

The process ID for this script is     : 149346
  • $$ = 149346(当前脚本的进程ID)

第10行输出

The exit status of this script is     : 0
  • $? = 0(上一条命令执行成功)

四、验证实验

# 验证 $10 vs ${10} 的区别
cat > test10.sh << 'EOF'
#!/bin/bash
echo "\$10 = $10"
echo "\${10} = ${10}"
EOF

bash test10.sh a b c d e f g h i j k
# 输出:
# $10 = a0    ($1 + "0")
# ${10} = j   (真正的第10个参数)

五、内存中的状态

# 执行时的内部状态
脚本进程PID: 149346
参数数组: ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m"]
参数个数: 13
当前用户: root
最后退出码: 0

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注