shell变量以及如何使用变量

SHELL变量


变量 (内存空间)

增加脚本的灵活性, 适用性 



类型:


自定义变量

环境变量(PATH)

特殊变量



自定义变量 


1 声明变量


# 变量名称=变量值


变量名称规范:

只能由数字、字母、下划线组成 

不能以数字开头 


[root@shell ~]# name=tom



2 调用变量的值

$变量名称

${变量名称} 变量名称后紧跟数字, 字符的时候


[root@shell ~]# name=cat


[root@shell ~]# echo "This is a $name"

This is a cat


[root@shell ~]# echo "There are some ${name}s"

There are some cats


SHELL变量的值默认全都作为字符处理


[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# c=a+b

[root@shell ~]# echo $c

a+b

[root@shell ~]# c=$a+$b

[root@shell ~]# echo $c

10+20

[root@shell ~]# 


3 如何使用变量的值作数学运算 


方法1: $((EXPRESSION))


[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# c=$((a+b))

[root@shell ~]# echo $c

30

[root@shell ~]# 



方法2: 关键字  let  


[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# let c=a+b

[root@shell ~]# echo $c

30

[root@shell ~]# 



方法3: 关键字  declare 


[root@shell ~]# a=10

[root@shell ~]# b=20

[root@shell ~]# declare -i c=a+b

[root@shell ~]# echo $c

30

[root@shell ~]# 



数学运算符: 

+

-

*

/ 整除

% 取余



生成10以内的随机数        echo $RANDOM   ------> 生成随机数


[root@shell ~]# echo $((RANDOM%10))

9

[root@shell ~]# echo $((RANDOM%10))

8

[root@shell ~]# echo $((RANDOM%10))

4

[root@shell ~]# echo $((RANDOM%10))

5



4 命令引用 


反引号 `COMMAND`

$(COMMAND)


[root@shell ~]# a=`ls -ldh /etc/`

[root@shell ~]# echo $a

drwxr-xr-x. 65 root root 4.0K 11月 20 16:32 /etc/

 

[root@shell ~]# b=$(ls -ldh /etc/)

[root@shell ~]# echo $b

drwxr-xr-x. 65 root root 4.0K 11月 20 16:32 /etc/

[root@shell ~]# 



5 删除变量 


# unset 变量名称



环境变量 


1) 查看环境变量 


[root@shell ~]# env

HOSTNAME=shell.linux.com

TERM=xterm

SHELL=/bin/bash

HISTSIZE=1000

SSH_CLIENT=192.168.122.1 44503 22

SSH_TTY=/dev/pts/0

USER=root



2) 定义环境变量, 修改环境变量的值


# export 变量名称=变量值


/etc/profile

/etc/bashrc





3) 特殊变量   $$   -----> shell本身的PID  

                           $! -----> shell最后运行的后台process的PID 

                           $0  -----> shell本身的参数个数   

                           $1~$n  ----> 添加到shell的各参数值。$1是第一个参数,依次排

                   $? 代表上一条命令的执行状态

                           0---255

                           0 执行成功


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章