Shell 命令行參數(shù)
在腳本中通過(guò) $1, $2, $3, 引用參數(shù)${10} 時(shí),參數(shù)必須在大括號(hào)中。
#!/bin/bash
# Call this script with at least 10 parameters, for example
# ./scriptname 1 2 3 4 5 6 7 8 9 10
MINPARAMS=10
echo
echo "The name of this script is \"$0\"."
# Adds ./ for current directory
echo "The name of this script is \"`basename $0`\"."
# Strips out path name info (see 'basename')
echo
if [ -n "$1" ] # Tested variable is quoted.
then
echo "Parameter #1 is $1" # Need quotes to escape #
fi
if [ -n "$2" ]
then
echo "Parameter #2 is $2"
fi
if [ -n "$3" ]
then
echo "Parameter #3 is $3"
fi
# ...
if [ -n "${10}" ] # Parameters > $9 must be enclosed in {brackets}.
then
echo "Parameter #10 is ${10}"
fi
echo "-----------------------------------"
echo "All the command-line parameters are: "$*""
if [ $# -lt "$MINPARAMS" ]
then
echo
echo "This script needs at least $MINPARAMS command-line arguments!"
fi
echo
exit 0
腳本的返回狀態(tài)
shell 中使用exit命令來(lái)結(jié)束腳本,就像C程序一樣,也會(huì)有一個(gè)返回值來(lái)給到父進(jìn)程。
每個(gè)命令都會(huì)返回一個(gè)exit狀態(tài),如果命令執(zhí)行成功,返回0。如果返回一個(gè)非零值,通常情況下都會(huì)認(rèn)為是一個(gè)錯(cuò)誤碼。
當(dāng)一個(gè)腳本不以exit退出時(shí),就用最后一個(gè)命令的返回碼來(lái)作為腳本的狀態(tài)。
在shell中,使用$?來(lái)讀取最后一個(gè)命令的退出碼。