分享

Shell中$0、$1、$#、$@、$*、$?、$的含义

 InfoRich 2024-01-19 发布于江苏

👉 $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.'
$ ./test2The shell is ./test2.The first parameter is .The first parameter is .
$ ./test2 a 2The shell is ./test2.The first parameter is a.The first parameter is 2.
$ ./test2 a b cThe shell is ./test2.The first parameter is a.The first parameter is b.

👉 $# 👇
$#传给脚本的参数个数
#!/bin/bash# test $#
echo 'The number of parametes is $#.'
$ ./test0The number of parametes is 0.
$ ./test0 1 2 3The number of parametes is 3.
$ ./test0 a bcThe number of parametes is 2.

👉 $@ 👇
$@传给脚本的所有参数的列表
#!/bin/bash# test $@
echo 'The parametes are $@.'
$ ./test1The parametes are .

$ ./test1 1 2 3The parametes are 1 2 3.

$ ./test1 a bcThe parametes are a bc.

👉 $* 👇
$*以一个单字符串显示所有向脚本传递的参数,与位置变量不同,参数可超过9个
./myscript.sh arg1 arg2 arg3
所有位置参数作为一个单词: $* = arg1 arg2 arg3逐个输出所有位置参数:arg1arg2arg3

👉 $? 👇
$?显示最后命令的退出状态,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
# 获取当前脚本的进程IDscript_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

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多