3 個實例介紹 shell 腳本中幾個特殊參數的用法
作者:佚名
在本文中討論的一些shell特殊參數是:$*,$@,$#,$$,$!
在本文中討論的一些shell特殊參數是:$*,$@,$#,$$,$!
示例1:使用 $*和$@ 來擴展位置參數
本實例腳本中使用$*和$@參數:
- [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
下面是運行結果:
- [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='-'表示使用" - "表示內部字段分隔符。
當打印參數$*的每個值時,它只給出一個值,即是IFS分隔的整個位置參數。
而$@將每個參數作為單獨的值提供。
示例2:使用$#統計位置參數的數量
$#是特殊參數,它可以提更腳本的位置參數的數量:
- [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"
下面是運行結果:
- [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 ]表示如果位置參數的數量小于2,則會提示"Usage: ./count.sh arg1 arg2"。
示例3:與過程相關的參數 $$和$!
參數$$將給出shell腳本的進程ID。$!提供最近執行的后臺進程的ID,下面實例是打印當前腳本的進程ID和最后一次執行后臺進程的ID:
- [root@localhost scripts]# vim proc.sh
- #!/bin/bash
- echo -e "Process ID=$$"
- sleep 1000 &
- echo -e "Background Process ID=$!"
下面是執行的結果:
- [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
責任編輯:龐桂玉
來源:
良許Linux