学习第三天 shell特殊变量
1、位置变量
$0 获取当前执行的Shell脚本的文件名,包括路径。
例1:
1 2 3 4 5 |
<strong>[root@test shell]# cat 0.sh #!/bin/bash echo $0 [root@test shell]# sh 0.sh 0.sh</strong> |
例2:
1 2 3 4 |
<strong>[root@test shell]# dirname /root/shell/0.sh /root/shell [root@test shell]# basename /root/shell/0.sh 0.sh</strong> |
1 2 3 4 |
<strong>[root@test shell]# cat 0.sh #!/bin/bash dirname "$0" basename "$0"</strong> |
1 2 3 |
<strong>[root@test shell]# sh /root/shell/0.sh /root/shell 0.sh</strong> |
注:dirname表示要得到脚本的路径,而basename表示要得到脚本的名称
$n 获取当前执行的Shell脚本的第n个参数值,n=1..9,当n为0时表示脚本的文件名,如果n大于9,用大括号括起来${10}
例1:
1 2 3 4 5 |
<strong>[root@test shell]# cat n.sh #!/bin/bash echo $1 $2 $3 [root@test shell]# sh n.sh a b c a b c</strong> |
例2:
1 2 3 4 5 |
<strong>[root@test shell]# cat n.sh #!/bin/bash echo $1 $2 $3 $8 [root@test shell]# sh n.sh a b c d e f g h i g k a b c h</strong> |
例3:
1 2 3 4 5 |
<strong>[root@test shell]# cat n.sh #!/bin/bash echo $1 $2 $3 $8 ${12} #注:这里的n的值>9所以要用{ } 括起来,表示12是一个整体# [root@test shell]# sh n.sh `seq 20` 1 2 3 8 12</strong> |
例4:
1 2 3 4 5 |
<strong>[root@test shell]# cat n.sh #!/bin/bash echo $1 $2 $3 $8 ${12} [root@test shell]# sh n.sh `seq 11` "this is my shell" </strong><strong>1 2 3 8 this is my shell</strong> |
注:如果其中有个参数中间是由空格隔开的,则需要将整个参数加上“”,表示这个参数为一个整体
从上面的例子可以看出:
n.sh后面的参数值分别赋予相对应的$n的值,以例2为例,如果shell里面有$5命令,则$5的值为e。
$* 获取当前Shell的所有参数,将所有的命令行参数视为单个字符串,相当于“$1$2$3”…注意与$#的区别
$# 获取当前Shell命令行中参数的总个数
例:
1 2 3 4 5 |
<strong>[root@test shell]# cat b.sh #!/bin/bash echo $# [root@test shell]# sh b.sh a b c d e f 6</strong> |
$@ 这个程序的所有参数“$1” “$2” “$3” “. . .”,这是将参数传递给其他程序的最佳方式,因为他会保留所有内嵌在每个参数里的任何空白。
版权声明:
作者:龙魂
链接:https://blog.wlzs.cn/%e5%ad%a6%e4%b9%a0%e7%ac%ac%e4%b8%89%e5%a4%a9-shell%e7%89%b9%e6%ae%8a%e5%8f%98%e9%87%8f/
来源:学海无涯
文章版权归作者所有,未经允许请勿转载。

共有 0 条评论