Shell变量的应用
· 用户自定义变量:由用户自己定义、修改和使用
· 预定义变量:Bash预定义的特殊变量,不能直接修改
· 位置变量:通过命令行给程序传递执行参数
变量的赋值与引用
定义新的变量
· 变量名要以英文字母或下划线开头,区分大小写
· 格式:变量名=变量值
查看变量的值
· 格式:echo $变量名
【root@bogon/】# abc=123
【root@bogon/】#echo $abc
123
删除变量
· 清除用户定义的变量
· 格式:unset 变量名
unset示例:
#!/bin/bash
#test.sh
name='user123'
unset name
echo $name
预定义变量
· 表示形式如下
· $#:命令行中位置参数的个数
· $*:所有位置参数的内容
· $?:上一条命令执行后返回的状态,当返回状态值为0时表示执行正常,非0值表示执行异常或出错
· $0:当前执行的进程/程序名
$0示例:
#!/bin/bash
#test.sh
echo "当前您正在执行的脚本的名称是:$0"
执行结果:
[root@bogon mnt]# ./test.sh
当前您正在执行的脚本的名称是:./test.sh
$#示例:
#!/bin/bash
#test.sh
echo $#
[root@bogon mnt]# ./test.sh 1 2 3 4 5
5
$*示例:
#!/bin/bash
#test.sh
echo "当前输出的脚本内容分别是:$*"
[root@bogon mnt]# ./test.sh 1 2 3 4 5
当前输出的脚本内容分别是:1 2 3 4 5
$?示例:
#!/bin/bash
#test.sh
ls
if [[ $? == 0 ]]; then
echo '上调命令执行成功'
else
echo '上调命令执行失败'
fi
[root@bogon mnt]# ./test.sh
test.sh
上调命令执行成功
#!/bin/bash
#test.sh
ll
if [[ $? == 0 ]]; then
echo '上调命令执行成功'
else
echo '上调命令执行失败'
fi
[root@bogon mnt]# ./test.sh
./test.sh: line 3: ll: command not found
上调命令执行失败
位置变量
· 表示为$n,n为1~9之间的数字
$n示例:
#!/bin/bash
#test.sh
echo $1
echo $2
echo $3
echo $4
echo $5
echo $6
echo $7
echo $8
echo $9
echo $10
[root@bogon mnt]# ./test.sh a b c d e f g h i j
a
b
c
d
e
f
g
h
i
a0#由于位置变量支持最大为9,所以第10位shell识别为$1,$1即为a,0无法识别,即最后一位输出结果为a0。
数值变量的运算
· 计算整数表达式的运算结果
· 格式:expr 变量1 运算符 变量2 ……【运算符 变量n】
· expr的常用运算符
· 加法运算:+
· 减法运算:-
· 乘法运算:\*
· 除法运算:/
· 求模(取余)运算:%
以下为:加减乘除求模示例:
[root@bogon mnt]# cat test.sh
#!/bin/bash
#test.sh
num=`expr 88887 + 2`
echo $num
[root@bogon mnt]# ./test.sh
88889
[root@bogon mnt]# cat test.sh
#!/bin/bash
#test.sh
num=`expr 88887 - 2`
echo $num
[root@bogon mnt]# ./test.sh
88885
[root@bogon mnt]# cat test.sh
#!/bin/bash
#test.sh
num=`expr 88887 \* 2`
echo $num
[root@bogon mnt]# ./test.sh
177774
[root@bogon mnt]# cat test.sh
#!/bin/bash
#test.sh
num=`expr 88887 / 2`
echo $num
[root@bogon mnt]# ./test.sh
44443
[root@bogon mnt]# cat test.sh
#!/bin/bash
#test.sh
num=`expr 88887 % 2`
echo $num
[root@bogon mnt]# ./test.sh
1