Bash测试是否存在参数

Ale*_*huk 7 testing bash command-line-arguments

我想测试是否将扩充(例如-h)传递到我的bash脚本中.

在Ruby脚本中,它将是:

#!/usr/bin/env ruby
puts "Has -h" if ARGV.include? "-h"
Run Code Online (Sandbox Code Playgroud)

如何在Bash中做到最好?

kit*_*ris 6

最简单的解决方案是:

if [[ " $@ " =~ " -h " ]]; then
   echo "Has -h"
fi
Run Code Online (Sandbox Code Playgroud)


Jon*_*ler 2

它相当复杂。最快的方法也是不可靠的:

case "$*" in
(*-h*) echo "Has -h";;
esac
Run Code Online (Sandbox Code Playgroud)

不幸的是,这也会将“ command this-here”视为具有“ -h”。

通常您会用来getopts解析您期望的参数:

while getopts habcf: opt
do
    case "$opt" in
    (h) echo "Has -h";;
    ([abc])
        echo "Got -$opt";;
    (f) echo "File: $OPTARG";;
    esac
done

shift (($OPTIND - 1))
# General (non-option) arguments are now in "$@"
Run Code Online (Sandbox Code Playgroud)

ETC。