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

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
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
1.4 預定義變量 ( $ \$0, \$*, \$@, \$\#, \$\$, \$!, \$? $ )
#!/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 '$$='$$
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
2. 環境變量(在目前shell和子shell有效)
2.1 export
echo "ip1 is $ip1"
echo "ip2 is $ip2"
(ip2 是環境變量)
2.2 在一個bash檔案中調用其他bash檔案
2.3 env 檢視所有環境變量
3. 指令代換: ` `或 $()
#! /bin/bash
pwd
ls
DATA=$(date)
echo $DATA
$(curl www.itcast.cn > 1.html)
pwd
4. 算術代換
4.1 $(()), expr
4.2 $[], let
5. 小數計算
echo "scale=3;6/4" |bc
awk 'BEGIN{print 1/2}'
6. 變量"内容"的删除和替換
6.1 從前往後删除(#:最近比對; ##:貪婪比對)
6.2 從後往前删除(%:最近比對; %%:貪婪比對)
6.3 索引方式切片
6.4 替換
貪婪比對
6.6 替代 ${變量名-新的變量值}
變量沒有被指派:會使用“新的變量值”替代
變量有被指派(包括空值):不會被替代