bash脚本参数

Bre*_*nt 11 parameters bash scripting

我需要编写一个bash脚本,并希望它解析格式的无序参数:

scriptname --param1 <string> --param2 <string> --param3 <date>
Run Code Online (Sandbox Code Playgroud)

有没有一种简单的方法来实现这一点,或者我几乎坚持1美元,2美元,3美元?

Lan*_*son 10

你想要getopts.

  • getopts不支持长开关(以 - 开头).getopt确实如此,但使用/读取它非常糟糕 (5认同)
  • 对于内容和/或示例,这个答案会更好,而不仅仅是一个链接. (3认同)

lhu*_*ath 8

while [[ $1 = -* ]]; do
    arg=$1; shift           # shift the found arg away.

    case $arg in
        --foo)
            do_foo "$1"
            shift           # foo takes an arg, needs an extra shift
            ;;
        --bar)
            do_bar          # bar takes no arg, doesn't need an extra shift
            ;;
    esac
done
Run Code Online (Sandbox Code Playgroud)