天天看點

Shell程式設計(四)Shell變量

1. 自定義變量(僅在目前shell生效)

1.1 定義變量

#!/usr/bin/bash
ip=115.239.210.27

if ping -c1 $ip &>/dev/null ;then    # &>/dev/null: output of ping $ip is null
    echo "$ip is up."
else
    echo "$ip is down."
fi      
Shell程式設計(四)Shell變量

1.2 輸入變量

#!/usr/bin/bash
read ip

ping -c1 $ip &>/dev/null
if [ $? -eq 0 ]; then
    echo "$ip is up."
else
    echo "$ip is down."
fi      
Shell程式設計(四)Shell變量

1.3 位置變量 ($1, $2, $3...${10}....)

#!/bin/bash
                       
ping -c1 $1 &>/dev/null
if [ $? -eq 0 ]; then
    echo "$1 is up."   
else
    echo "$1 is down." 
fi      
Shell程式設計(四)Shell變量

1.4 預定義變量 ( $ \$0, \$*, \$@, \$\#, \$\$, \$!, \$? $ )

Shell程式設計(四)Shell變量
#!/bin/bash
echo "the par of 2: $2"
echo "the par of 1: $1"
echo "the par of 4: $4"

echo "all par: $*"     
echo "all par: $@"     
echo "the num of par: $#"
echo "the PID of cur process: $$"
  
echo '$1='$1           
echo '$2='$2           
echo '$3='$3           
echo '$*='$*           
echo '$@='$@           
echo '$#='$#
echo '$$='$$       
Shell程式設計(四)Shell變量
Shell程式設計(四)Shell變量

1.5 綜合

#!/bin/bash
# if user have no parma
if [ $# -eq 0 ]; then  
    echo "usage: `basename $0` file"
fi


if [ ! -f $1 ]; then     # not a file
    echo "erro file!"  
fi
  
echo "ping........."   
  
for ip in `cat $1`     
do
    ping -c1 $ip &>/dev/null
    if [ $? -eq 0 ];then    
        echo "$ip is up."       
    else
        echo "$ip is down."     
    fi
done      
Shell程式設計(四)Shell變量

2. 環境變量(在目前shell和子shell有效)

2.1 export

echo "ip1 is $ip1"
echo "ip2 is $ip2"      
Shell程式設計(四)Shell變量
Shell程式設計(四)Shell變量

(ip2 是環境變量)

2.2  在一個bash檔案中調用其他bash檔案

Shell程式設計(四)Shell變量

2.3 env 檢視所有環境變量

3. 指令代換: ` `或 $()

Shell程式設計(四)Shell變量
#! /bin/bash

pwd
ls

DATA=$(date)

echo $DATA

$(curl www.itcast.cn > 1.html)

pwd      
Shell程式設計(四)Shell變量

4. 算術代換

4.1 $(()), expr

4.2 $[], let

Shell程式設計(四)Shell變量

5. 小數計算

echo "scale=3;6/4" |bc      
Shell程式設計(四)Shell變量
awk 'BEGIN{print 1/2}'      
Shell程式設計(四)Shell變量

 6. 變量"内容"的删除和替換

Shell程式設計(四)Shell變量

6.1 從前往後删除(#:最近比對; ##:貪婪比對)

Shell程式設計(四)Shell變量

6.2 從後往前删除(%:最近比對; %%:貪婪比對)

Shell程式設計(四)Shell變量
Shell程式設計(四)Shell變量

6.3 索引方式切片

Shell程式設計(四)Shell變量

6.4 替換

Shell程式設計(四)Shell變量

貪婪比對

Shell程式設計(四)Shell變量

6.6 替代 ${變量名-新的變量值}

變量沒有被指派:會使用“新的變量值”替代

變量有被指派(包括空值):不會被替代

6.61 - 和 :-

Shell程式設計(四)Shell變量

6.62 + 和 :+

Shell程式設計(四)Shell變量

6.63 = 和 :=

6.64 ? 和 :?