特殊参数变量:
$#
:传给Shell脚本的参数个数
$0
:当前Shell脚本名
$1
:传递给Shell脚本的第1个参数,若没有则为空
$2
:传递给Shell脚本的第2个参数,若没有则为空
$3
:传递给Shell脚本的第3个参数,后续以此类推
${10}
:传递给Shell脚本的第10个参数,读取的参数位置大于等于10之后需要使用花括号
$@
:传递给Shell脚本的所有参数组成的列表,即参数列表
$*
:传递给Shell脚本的的所有参数组成的单个字符串,不同参数之间空格依旧存在
特殊状态变量:
$?
:上一指令的退出码(既可以是执行脚本程序指令也可以是普通命令),0表示正常退出,其余表示异常
$$
:当前Shell的PID
$!
:获取上一个后台执行的Shell的PID(若不在运行,则返回空)
$_
:获取上一个执行指令,如果执行指令有参数,则返回指令的最后一个参数(如执行脚本)
测试脚本:
#!/bin/bash
# test8:用于练习特殊参数变量
echo "The number of parameters is $#"
echo "The current script is $0"
echo "The first parameter is $1"
echo "The parameter-10 is ${10}"
echo "The parameters string is $*"
# 使用shift命令可以将参数列表前移指定次数,每次移动一次则覆盖一次$1,参数个数减1
shift 1
echo "The parameters list is $@"
# 用于练习特殊状态变量
date
echo "The last command or parameter is $_"
date +%Y-%m-%d
echo "The last command or parameter is $_"
echo "123"> tmp &
echo "The last command exit code is $?"
echo "The last background shell PID is $!"
echo "The current shell PID is $$"
测试脚本输出:
root@localhost:~/script_test# ./test8 1 2 3 4 5 6
The number of parameters is 6
The current script is ./test8
The first parameter is 1
The parameter-10 is
The parameters string is 1 2 3 4 5 6
The parameters list is 2 3 4 5 6
Mon Feb 17 10:57:17 CST 2020
The last command or parameter is date
2020-02-17
The last command or parameter is +%Y-%m-%d
The last command exit code is 0
The last background shell PID is 460
The current shell PID is 457