bash getopts多个参数或默认值

Gre*_*reg 6 bash shell scripting getopts

所以我有一个关于在bash中获取opts的问题.我想获取参数的值,如果它们存在但是如果它们不存在则使用默认值.因此脚本应该采用目录和整数,但如果未指定,则$ PWD和3应为默认值.这是什么

while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        \? ) usage
        exit 1;;
    esac
Run Code Online (Sandbox Code Playgroud)

anu*_*ava 16

你可以在while循环之前提供默认值:

directory=mydir
depth=123
while getopts "hd:l:" opt; do
    case $opt in
        d ) directory=$OPTARG;;
        l ) depth=$OPTARG;;
        h ) usage
        exit 0;;
        *) usage
        exit 1;;
    esac
done
echo "<$directory> <$depth>"
Run Code Online (Sandbox Code Playgroud)

  • 我还需要谦虚地指出,这个问题是关于设置我的答案提供的默认值。在接受这个答案后,再问一个关于目录更改问题的单独问题不是更好吗? (2认同)