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 執行成功


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