shell 变量
- 什么是shell变量
- 变量的类型
- 变量的定义方式
- 变量的运算
- 变量“内容”的删除和替换
shell变量? 用一个特定的字符串去表示不固定的内容
变量的类型
- 自定义变量
- 定义变量:变量名=变量值 变量名必须以字母或下划线开头,区分大小写
- 引用变量:
- $变量名
- 或 ${变量名}
- 查看变量:echo $变量名 set(所有变量:包括自定义变量和环境变量)
- 取消变量:unset 变量名
- 作用范围:仅在当前shell中有效
[root@x scripts]# ./ping01.sh 引用变量
www.baidu.com ip up
[root@x scripts]# echo $ip 查看变量
www.baidu.com
[root@x scripts]# ./ping02.sh
up
[root@x scripts]# ./ping03.sh
up
[root@x scripts]# ./ping04.sh
192.168.1.12
up
[root@x scripts]# ./ping04.sh
192.168.1.22
down
read 从键盘读入
[root@x scripts]# ./ping04.sh
Please input a ip:192.168.1.12:192.168.1.12
up
注意:以字母和下划线开始
方式:写入和read
第一个参数为$1,第二个参数为$2;
[root@x scripts]# ./ping05.sh
down
[root@x scripts]# ./ping05.sh 192.168.1.12 10.1.1.1
192.168.1.12 up
[root@x scripts]# ./ping05.sh 10.1.1.1 192.168.1.12
10.1.1.1 down
$1:位置变量
-
变量环境
-
定义环境变量:
- 方法一:export back_dir2=/home/backup
- 方法二:export back_dir1 将自定义变量名转换成环境变量
-
引用环境变量:
- $变量名
- 或 ${变量名}
-
查看环境变量:echo $变量名 env 例如env | grep back_dir2
-
取消环境变量:unset 变量名
-
变量作用范围:在当前shell和子shell有效
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = == = = = = = = = = = = = = = =
[root@x scripts]# source public.sh
[root@x scripts]# ./1.sh
ip10