如何在 bash 中打印用法和缺少参数错误



我有一个需要 5 个参数的 bash 脚本。我想打印用法和缺少参数错误(如果缺少其中任何一个并在那里退出(。还有帮助选项,只需打印$usage。

#script.sh
usage="$0 param1 param2 param3 param4 param5
         param1 is ..
         param2 is ..
         param3 is ..
         param4 is ..
         param5 is .."
#if script.sh
# prints $usage and all param missing
#if script.sh param1 param2 param3
# print $usage and param4 and param5 missing and exit and so on
# script.sh -h
# just print $usage
您可以使用

var=${1:?error message}

如果设置了$1的值,则$var存储该值,如果未设置,则显示error message并停止执行。

例如:

src_dir="${1:?Missing source dir}"
dst_dir="${2:?Missing destination dir}"
src_file="${3:?Missing source file}"
dst_file="${4:?Missing destination file}"
# if execution reach this, nothing is missing
src_path="$src_dir/$src_file"
dst_path="$dst_dir/$dst_file"
echo "Moving $src_path to $dst_path"
mv "$src_path" "$dst_path"

这里有一种方法可以做到这一点:

usage() {
    echo the usage message
    exit $1
}
fatal() {
    echo error: $*
    usage 1
}
[ "$1" = -h ] && usage 0
[ $# -lt 1 ] && fatal param1..param5 are missing
[ $# -lt 2 ] && fatal param2..param5 are missing
[ $# -lt 3 ] && fatal param3..param5 are missing
[ $# -lt 4 ] && fatal param4 and param5 are missing
[ $# -lt 5 ] && fatal param5 is missing
# all good. the real business can begin here

另一种方法。

if [ $# -ne 5 ]
then
    echo "$0 param1 param2 param3 param4 param5
          You entered $# parameters"
    PC=1
    for param in "$@"
    do
       echo "param${PC} is $param"
       PC=$[$PC +1]
    done
fi

最新更新