shell脚本位置变量

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 $* 与 $@ 的区别

下述内容的详细解释:

  1. 执行f1脚本前两行,表示不打双引号时, 两者都表示全部字符,正常输出;
  2. 然后执行file脚本,此处"$*"是对于f1的参数而言,表示abc视为一个字符,因此$1即为abc
  3. 对于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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值