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

时间:2015-10-17 18:29:11

标签: 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

3 个答案:

答案 0 :(得分:3)

您可以使用

var=${1:?error message}

如果设置了$var,则$1存储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" 并停止执行。

例如:

.professor-list

答案 1 :(得分:1)

这是一种方法:

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

答案 2 :(得分:0)

另一种方法。

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