Shell 命令行参数
在脚本中通过 $1, $2, $3, 引用参数${10} 时,参数必须在大括号中。
#!/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
脚本的返回状态
shell 中使用exit命令来结束脚本,就像C程序一样,也会有一个返回值来给到父进程。
每个命令都会返回一个exit状态,如果命令执行成功,返回0。如果返回一个非零值,通常情况下都会认为是一个错误码。
当一个脚本不以exit退出时,就用最后一个命令的返回码来作为脚本的状态。
在shell中,使用$?来读取最后一个命令的退出码。