3.8 位置变量🤣
1 含义
在bash shell中内置的变量, 在脚本代码中调用的通过命令行传递给脚本的参数
$1, $2, ... 对应第1个、第2个等参数,shift [n]换位置
$0 表示脚本文件本身,包括路径
$* 传递给脚本的所有参数'全部参数合为一个字符串
$@ 传递给脚本的所有参数'每个参数为独立字符串
$# 传递给脚本的参数 的个数
注意:$@ $* 只在被双引号包起来的时候才会有差异
=
2 清空所有位置变量
set --
=
3 功能解释
#!/bin/bash
echo "1st arg is $1"
echo "2nd arg is $2"
echo "3rd arg is $3"
echo "the number of arg is $#"
echo "all args are $*"
echo "all args are $@"
echo "the scriptname is `basename $0`"
1st arg is caokunzi
2nd arg is zhubazi
3rd arg is 2020
the number of arg is 3
all args are caokunzi zhubazi 2020
all args are caokunzi zhubazi 2020
the scriptname is arg.sh
=
4 应用——防止删根
重要:删库跑路命令 rm 的安全实现
#!/bin/bash
WARNING_COLOR="echo -e \e[1;31m"
END="\E[0m"
DIR=/tmp/`date +%F_%T`
mkdir $DIR
mv $* $DIR
${WARNING_COLOR} move $* to $DIR $END
[root@centos8/~]# alias rm='/data/scripts/rm.sh'
=
5 $* 与 $@ 的区别
下述内容的详细解释:
-
执行f1脚本前两行,表示不打双引号时, 两者都表示全部字符,正常输出;
-
然后执行file脚本,此处
"$*"
是对于f1的参数而言,表示abc视为一个字符,因此$1
即为abc -
对于f2脚本,此处
"$@"
是表示将abc视为单个字符处理,因此f2最后的$1
表示a
[root@centos8/~]# cat file.sh # 脚本file输出$1
#!/bin/bash
echo "file.sh:1st arg is $1"
[root@centos8/~]# cat f1.sh
#!/bin/bash
echo "f1.sh:all args are $@"
echo "f1.sh:all args are $*"
./file.sh "$*" # 脚本f1最后运行file脚本
[root@centos8/~]# cat f2.sh
#!/bin/bash
echo "f1.sh:all args are $@"
echo "f1.sh:all args are $*"
./file.sh "$@" # 脚本f2最后运行file脚本
[root@centos8/~]# bash f1.sh a b c
f1.sh:all args are a b c
f1.sh:all args are a b c
file.sh:1st arg is a b c 说明 "$*" 表示的$1是 全部参数合体
[root@centos8/~]# bash f2.sh a b c
f1.sh:all args are a b c
f1.sh:all args are a b c
file.sh:1st arg is a 说明 "$@" 表示的$1是 单独的第一个参数
=
=
6 其他应用
利用软链接实现同一个脚本的不同功能
[root@centos8/~]# cat test.sh
#!/bin/bash
#*************************
echo $0 # 输出自己的basename
[root@centos8/~]# ll
total 4
lrwxrwxrwx. 1 root root 7 Aug 6 21:18 a.sh -> test.sh
lrwxrwxrwx. 1 root root 7 Aug 6 21:18 b.sh -> test.sh
-rwxr-xr-x. 1 root root 47 Aug 6 21:16 test.sh
[root@centos8/~]# ./a.sh
./a.sh # 软链接a.sh运行,则输出自己为a
[root@centos8/~]# ./b.sh
./b.sh # 软链接b.sh运行,则输出自己为b
= wan