一、环境变量
- 环境变量也可叫全局变量,可以在创建他们的shell及派生出的子shell中使用(无需定义,直接可以使用,如:$UID)
- 相关命令:
set :输出所有变量
env:只显示全局变量
declare:输出所有变量,函数,整数等
二、普通变量
- 普通变量赋值
变量名=value
变量名=‘value’
变量名=“value”
注意:建议没有特别要求时,字符串都加双引号,需要原样输出就加单引号
[root@server ~]# a=hello
[root@server ~]# echo $a
hello
[root@server ~]# b='hello'
[root@server ~]# echo $b
hello
[root@server ~]# c="hello"
[root@server ~]# echo $c
hello
[root@server ~]# a=westos-$a
[root@server ~]# echo $a
westos-hello
[root@server ~]# b='westos-$a' ##不转译变量,按原样输出
[root@server ~]# echo $b
westos-$a
[root@server ~]# c="westos-$a" ##转移变量
[root@server ~]# echo $c
westos-westos-hello
[root@server ~]# a=westos hello ##定义变量有空格时,要加“”
bash: hello: command not found...
[root@server ~]# a="westos hello"
[root@server ~]# echo $a
westos hello
- 命令结果作为内容赋值
变量名=命令
b=ls
或 b=$(ls)
[root@server mnt]# CMD=`ls -l`
[root@server mnt]# echo $CMD
total 8 -rwxr-xr-x. 1 root root 492 Dec 22 10:25 test.sh -rwxr-xr-x. 1 root root 40 Dec 22 10:40 westos.sh
[root@server mnt]# CMD=$(ls -l)
[root@server mnt]# echo $CMD
total 8 -rwxr-xr-x. 1 root root 492 Dec 22 10:25 test.sh -rwxr-xr-x. 1 root root 40 Dec 22 10:40 westos.sh
三、特殊变量
$0:获取shell脚本文件名,如果执行时包含路径,则输出脚本路径
$n(>0):获取脚本的第n个参数
$#:获取脚本后参数的总个数
$*:获取所有参数
$@:获取所有参数
$?:获取上一条命令执行状态的返回值,非0为失败
$$:获取当前shell进程号
$0
[root@server mnt]# cat westos.sh
#!/bin/bash
echo $0
[root@server mnt]# sh westos.sh
westos.sh
[root@server mnt]# /mnt/westos.sh
/mnt/westos.sh
$n
[root@server mnt]# cat westos.sh
#!/bin/bash
echo $1 $2
[root@server mnt]# sh westos.sh hello westos
hello westos
[root@server mnt]# sh westos.sh hello redhat
hello redhat
[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 {a..z}
a b c d e f g h i a0
[root@server mnt]# cat westos.sh
$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 j
$#
[root@server mnt]# cat westos.sh
echo $#
[root@server mnt]# sh westos.sh {1..100}
100
$?
[root@server mnt]# ls /etc/passwd
/etc/passwd
[root@server mnt]# echo $?
0
[root@server mnt]# ls /etc/password
ls: cannot access /etc/password: No such file or directory
[root@server mnt]# echo $?
2
$$
[root@server mnt]# echo $$
2795
[root@server mnt]# ps
PID TTY TIME CMD
2795 pts/2 00:00:00 bash
4277 pts/2 00:00:00 ps
四、read用法
[root@server mnt]# read str
westos hello
[root@server mnt]# echo $str
westos hello
[root@server mnt]# read -p "请输入一个整数:" i
请输入一个整数:10
[root@server mnt]# echo $i
10
五、练习
- 打包日志:(打包成log_yyyy-mm-dd.tar.gz的格式 )
[root@server mnt]# tar zcf log_$(date +%F).tar.gz /var/log/
tar: Removing leading `/' from member names
[root@server mnt]# ls
log_2018-12-22.tar.gz test.sh westos.sh