一、定义变量
注意:建议没有特别要求时,字符串都加双引号,需要原样输出就加单引号
二、特殊变量
$0:获取脚本文件名,如果执行时包含路径,则输出脚本路径
$n(>0): ##变量
$#:
$*:
$@:
$0:
[root@localhost mm]# vim westos.sh
[root@localhost mm]# sh westos.sh
westos.sh
[root@localhost mm]# chmod +x westos.sh
[root@localhost mm]# /mm/westos.sh
/mm/westos.sh
[root@localhost mm]#
$n:
[root@localhost mm]# cat westos.sh
#!/bin/bash
echo $1 $2
[root@localhost mm]# sh westos.sh hello world
hello world
[root@localhost mm]# sh westos.sh hello hello
hello hello
[root@server mnt]# echo \${1..10} > westos.sh
[root@server mnt]# cat westos.sh
$1 $2 $3 $4 $5 $6 $7 $8 $9 $10
[root@server mnt]# sh westos.sh {1..10}
1 2 3 4 5 6 7 8 9 10
[root@server mnt]# sh westos.sh {a..z}
a b c d e f g h i a0
[root@server mnt]# sh westos.sh {a..z}
a b c d e f g h i j
$#:
[root@localhost mm]# cat westos.sh
echo $1 $2 $3 $4 $5 $6 $7 $8 $9 $10
echo $#
[root@localhost mm]# sh westos.sh {1..100}
1 2 3 4 5 6 7 8 9 10
100
$?:
表示上条命令执行结果的返回值
0表示执行成功
非0表示执行失败
三、read用法
[root@localhost mm]# read -p "请输入一个整数:" i
请输入一个整数:1
四、将命令的结果赋值给变量
[root@localhost mm]# CMD=`ls -l`
[root@localhost mm]# echo $CMD
total 4 -rwxr-xr-x. 1 root root 44 Dec 25 19:36 westos.sh
[root@localhost mm]# SS=`ls`
[root@localhost mm]# echo $SS
westos.sh
五、练习
打包日志:
[root@localhost mm]# tar zcf log_$(date +%Y-%m-%s).tar.gz /var/log
tar: Removing leading `/' from member names
[root@localhost mm]# ls
log_2018-12-1545738492.tar.gz westos.sh
[root@localhost mm]# tar zcf log1_$(date +%F).tar.gz /var/log
tar: Removing leading `/' from member names
[root@localhost mm]# ls
log1_2018-12-25.tar.gz log_2018-12-1545738492.tar.gz westos.sh