👉 $0、$1、$2 👇 $0 | 脚本本身的名字 | $1 | 传递给该shell脚本的第一个参数 | $2 | 传递给该shell脚本的第二个参数 |
#!/bin/bash # test $0,$1
echo 'The shell is $0.' echo 'The first parameter is $1.' echo 'The first parameter is $2.'
$ ./test2 The shell is ./test2. The first parameter is . The first parameter is .
$ ./test2 a 2 The shell is ./test2. The first parameter is a. The first parameter is 2.
$ ./test2 a b c The shell is ./test2. The first parameter is a. The first parameter is b.
#!/bin/bash # test $#
echo 'The number of parametes is $#.'
$ ./test0 The number of parametes is 0.
$ ./test0 1 2 3 The number of parametes is 3.
$ ./test0 a bc The number of parametes is 2.
#!/bin/bash # test $@
echo 'The parametes are $@.'
$ ./test1 The parametes are .
$ ./test1 1 2 3 The parametes are 1 2 3.
$ ./test1 a bc The parametes are a bc.
$* | 以一个单字符串显示所有向脚本传递的参数,与位置变量不同,参数可超过9个 |
./myscript.sh arg1 arg2 arg3
所有位置参数作为一个单词: $* = arg1 arg2 arg3 逐个输出所有位置参数: arg1 arg2 arg3
$? | 显示最后命令的退出状态,0表示没有错误,其他表示有错误 |
#!/bin/bash
# 运行一个成功的命令 ls /tmp
# 检查上一个命令的退出状态 if [ $? -eq 0 ]; then echo 'ls 命令执行成功' else echo 'ls 命令执行失败' fi
# 运行一个失败的命令 cat /nonexistentfile.txt
# 检查上一个命令的退出状态 if [ $? -eq 0 ]; then echo 'cat 命令执行成功' else echo 'cat 命令执行失败' fi
$$ | 脚本运行的当前进程ID号 | 构造一个临时文件名,确保它在脚本执行时是唯一的 |
#!/bin/bash
# 获取当前脚本的进程ID script_pid=$$
echo '当前脚本的进程ID为: $script_pid'
# 可以使用$script_pid进行其他处理,例如输出到日志文件、构建唯一文件名等等 log_file='/var/log/mylog_$script_pid.log' echo '将日志写入文件: $log_file'
# 模拟一些工作,例如将一些信息写入日志文件 echo '这是一些示例日志信息' >> '$log_file'
echo '工作完成。'
#!/bin/bash
echo '当前脚本的进程ID为: $$'
# 使用$$创建一个唯一的临时文件名 temp_file='/tmp/mytempfile_$$.txt' echo '正在创建临时文件: $temp_file'
# 模拟一些工作,例如写入一些数据到临时文件 echo '这是一些示例数据' > '$temp_file'
echo '工作完成,临时文件已创建。'
# 在脚本结束时删除临时文件 rm '$temp_file' echo '临时文件已删除。'
参考链接 https://www.jianshu.com/p/03b6fa705a82
|