shell 特殊的位置参数变量

$1 $2 $3 ... ${10} ${11}
$0
$#
$*
$@



################   $1 $2 $3 ... ${10} ${11} 实践  #######################
$ cat hello.sh 
echo $1 $2
(( sum=$1+$2 ))
echo $sum
$ bash hello.sh 2 5
2 5
7



###############   $0 dirname basename 实践  #################################
$ cat /home/dc2-user/dir/child/hello.sh
echo $0
$ cd /home/dc2-user/dir/child && bash hello.sh 
hello.sh
$ cd /home
$ bash ./dc2-user/dir/child/hello.sh 
./dc2-user/dir/child/hello.sh
$ bash dc2-user/dir/child/hello.sh 
dc2-user/dir/child/hello.sh
通过上面的例子我们可以看到 $0 是打印当前执行脚本的全路径,输出的结果与我们如何表示文件路径的方式有关(绝对路径 相对路径 等)

如果我们想要单独拿到执行的目录或者文件名的部分,就需要用到 dirname 和 basename
$ dirname /home/dc2-user/dir/child/hello.sh
/home/dc2-user/dir/child
$ basename /home/dc2-user/dir/child/hello.sh
hello.sh
$ cd /home && basename dc2-user/dir/child/hello.sh
hello.sh
$ cd /home && dirname dc2-user/dir/child/hello.sh
dc2-user/dir/child



#############################  $# 位置参数实践  ###################################
$ cat q.sh
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 ${10} ${11}
echo $#
$ bash q.sh {1..20}
1 2 3 4 5 6 7 8 9 10 11
20
可以看到 $# 是用来确定实际传入脚本的参数个数,比如某些时候我们写的脚本要求必须传入2个参数,不能多不能少,我们就可以利用这个 $# 来实现,如下
$ cat q2.sh
if [ $# -ne 2 ]; then
    echo "USAGE: /bin/bash $0 arg1 arg2"
    echo "参数必须是两个"
    exit
fi
echo "bula bula bula"
$ bash  q2.sh 
USAGE: /bin/bash q2.sh arg1 arg2
参数必须是两个
$ bash  ~/q2.sh 
USAGE: /bin/bash /home/dc2-user/q2.sh arg1 arg2
参数必须是两个

猜你喜欢

转载自blog.csdn.net/xys2015/article/details/112575912