如何编写一个提供默认参数的非常简单的包装器?

Tob*_*ler 5 bash parameter shell-script

给定一个需要一些参数的程序,例如program -in file.in -out file.out,编写一个可以使用或不使用任何这些参数调用并为每个参数使用默认值的 bash 脚本的最简单方法是什么?

script -in otherfile会跑program -in otherfile -out file.out
script -out otherout -furtherswitch会跑program -in file.in -out otherout -furtherswitch等等。

l0b*_*0b0 7

在 Bash 中很容易定义默认值:

foo="${bar-default}" # Sets foo to the value of $bar if defined, "default" otherwise
foo="${bar:-default}" # Sets foo to the value of $bar if defined or empty, "default" otherwise
Run Code Online (Sandbox Code Playgroud)

要处理您的参数,您可以使用一个简单的循环:

while true
do
    case "${1-}" in
        -in)
            infile="${2-}"
            shift 2
            ;;
        -out)
            outfile="${2-}"
            shift 2
            ;;
        *)
            break
            ;;
    esac
done

program -in "${infile-otherfile}" -out "${outfile-otherout}" "$@"
Run Code Online (Sandbox Code Playgroud)

有用的读物​​:

我还建议getopt改用它,因为它能够处理许多特殊情况,这些情况会很快使您的代码变得复杂和混乱(非平凡示例)。