3 個(gè)實(shí)例介紹 shell 腳本中幾個(gè)特殊參數(shù)的用法
在本文中討論的一些shell特殊參數(shù)是:$*,$@,$#,$$,$!
示例1:使用 $*和$@ 來擴(kuò)展位置參數(shù)
本實(shí)例腳本中使用$*和$@參數(shù):
- [root@localhost scripts]# vim expan.sh
- #!/bin/bash
- export IFS='-'
- cnt=1
- # Printing the data available in $*
- echo "Values of \"\$*\":"
- for arg in "$*"
- do
- echo "Arg #$cnt= $arg"
- let "cnt+=1"
- done
- cnt=1
- # Printing the data available in $@
- echo "Values of \"\$@\":"
- for arg in "$@"
- do
- echo "Arg #$cnt= $arg"
- let "cnt+=1"
- done
下面是運(yùn)行結(jié)果:
- [root@localhost scripts]# ./expan.sh "Hello world" 2 3 4
- Values of "$*":
- Arg #1= Hello world-2-3-4
- Values of "$@":
- Arg #1= Hello world
- Arg #22= 2
- Arg #33= 3
- Arg #44= 4
export IFS='-'表示使用" - "表示內(nèi)部字段分隔符。
當(dāng)打印參數(shù)$*的每個(gè)值時(shí),它只給出一個(gè)值,即是IFS分隔的整個(gè)位置參數(shù)。
而$@將每個(gè)參數(shù)作為單獨(dú)的值提供。
示例2:使用$#統(tǒng)計(jì)位置參數(shù)的數(shù)量
$#是特殊參數(shù),它可以提更腳本的位置參數(shù)的數(shù)量:
- [root@localhost scripts]# vim count.sh
- #!/bin/bash
- if [ $# -lt 2 ]
- then
- echo "Usage: $0 arg1 arg2"
- exit
- fi
- echo -e "\$1=$1"
- echo -e "\$2=$2"
- let add=$1+$2
- let sub=$1-$2
- let mul=$1*$2
- let div=$1/$2
- echo -e "Addition=$add\nSubtraction=$sub\nMultiplication=$mul\nDivision=$div\n"
下面是運(yùn)行結(jié)果:
- [root@localhost scripts]# ./count.sh
- Usage: ./count.sh arg1 arg2
- [root@localhost scripts]# ./count.sh 2314 15241
- $1=2314
- $2=15241
- Addition=17555
- Subtraction=-12927
- Multiplication=35267674
- Division=0
腳本中if [ $# -lt 2 ]表示如果位置參數(shù)的數(shù)量小于2,則會提示"Usage: ./count.sh arg1 arg2"。
示例3:與過程相關(guān)的參數(shù) $$和$!
參數(shù)$$將給出shell腳本的進(jìn)程ID。$!提供最近執(zhí)行的后臺進(jìn)程的ID,下面實(shí)例是打印當(dāng)前腳本的進(jìn)程ID和最后一次執(zhí)行后臺進(jìn)程的ID:
- [root@localhost scripts]# vim proc.sh
- #!/bin/bash
- echo -e "Process ID=$$"
- sleep 1000 &
- echo -e "Background Process ID=$!"
下面是執(zhí)行的結(jié)果:
- [root@localhost scripts]# ./proc.sh
- Process ID=14625
- Background Process ID=14626
- [root@localhost scripts]# ps
- PID TTY TIME CMD
- 3665 pts/0 00:00:00 bash
- 14626 pts/0 00:00:00 sleep
- 14627 pts/0 00:00:00 ps