linux中shell 特殊变量$0 $n $* $@ $! $?的详解
2019/10/10/17:46:31 阅读:1856 来源:谷歌SEO算法 标签:
SEO工具
我们知道在shell命令中有很多的变量,今天下文要讲到的是特殊变量$0 $n $* $@ $! $?详解,希望下文能帮助到各位朋友哦.
$0:获取当前执行脚本的文件名,包括路径.
- [root@testscript]#cat0.sh
- #!/bin/bash
- echo$0
- [root@testscript]#sh0.sh
- 0.sh
- [root@testscript]#cat0.sh
- #!/bin/bash
- dirname"$0"
- basename"$0"
- [root@testscript]#sh/byrd/script/0.sh
- /byrd/script
- 0.sh
$n:获取当前执行的shell脚本的第N个参数,n=1..9,当n为0时表示脚本的文件名,如果n大于9,用大括号括起来like${10}.
- [root@testscript]#catn.sh
- #!/bin/bash
- echo$1$2${10}
- [root@testscript]#shn.shabcdefghijklmn
- abj
- [root@LAMPscript]#shn.sh{a..z}
- abj
- [root@testscript]#shn.sh`seq11`
- 1210
$*:获取当前shell的所有参数,将所有的命令行参数视为单个字符串.
$@:这个程序的所有参数"$1" "$2" "$3" "...",这是将参数传递给其他程序的最佳方式,因此TA会保留所有内嵌在每个参数里的任何空白.
$#:获取当前shell命令行中参数的总个数。
- [root@testscript]#cathashtag.sh
- #!/bin/bash
- echo"$#"
- [root@testscript]#shhashtag.sh
- 0
- [root@testscript]#shhashtag.sh123
- 3
- [root@testscript]#shhashtag.sh`seq300`
- 300
- [root@testscript]#catexample.sh
- #!/bin/bash
- #Example
- if[$#-ne2];then
- echo"Error,pleaseentertwoparameters."
- exit1
- else
- echo"Youdidagoodjob."
- fi--phpfensi.com
- [root@testscript]#shexample.sha
- Error,pleaseentertwoparameters.
- [root@testscript]#shexample.shab
- Youdidagoodjob.
- [root@testscript]#shexample.shabc
- Error,pleaseentertwoparameters.
$_:代表上一个命令的最后一个参数
$$:代表所在命令的PID
- [root@LAMPscript]#catdollar.sh
- #!/bin/bash
- echo"$$">/tmp/dollar.pid
- whiletrue
- do
- sleep1
- done
- [root@LAMPscript]#shdollar.sh
- ################################################
- [root@LAMP~]#cat/tmp/dollar.pid
- 1483
- [root@LAMP~]#ps-ef|grep1483
- root14831453014:58pts/100:00:00shdollar.sh
- root15321483014:58pts/100:00:00sleep1
- root15341496014:58pts/000:00:00grep1483
- [root@LAMP~]#ps-ef|grepdollar
- root14831453014:58pts/100:00:00shdollar.sh
- root15551496014:58pts/000:00:00grepdollar
$!:代表最后执行的后台命令的PID
$?:代表上一个命令执行是否成功的标志,如果执行成功则$? 为0,否则不为0.
- [byrd@LAMPscript]$pwd
- /byrd/script
- [byrd@LAMPscript]$echo$?
- 0#运行成功
- [byrd@LAMPscript]$ls/root
- ls:cannotopendirectory/root:Permissiondenied
- [byrd@LAMPscript]$echo$?
- 2#权限拒绝
- [byrd@LAMPscript]$hahaha
- -bash:hahaha:commandnotfound
- [byrd@LAMPscript]$echo$?
- 127#未找到该命令
- ###########################################
- [byrd@LAMP~]$cat/byrd/script/question_mark.sh
- #!/bin/bash
- #Example
- ls-al/root>/dev/null2>&1
- if[$?-eq0];then
- echo"Userisroot"
- else
- echo"Theuserisnotroot"
- fi
- [root@LAMPscript]#shquestion_mark.sh
- Userisroot
- [root@LAMPscript]#su-byrd
- [byrd@LAMP~]$sh/byrd/script/question_mark.sh
- Theuserisnotroot
热门评论