シェルスクリプトでスイッチを処理する方法は?

シェルスクリプトでスイッチを処理する方法は?

-xパラメータの代わりにスイッチを認識する組み込みツールはありますか--xxxx?または、すべての入力変数を繰り返してダッシュをテストし、パラメータを解析する必要がありますか?

ベストアンサー1

私はあなたがbashまたは同様のものを使用していると仮定します。一例:

all=false
long=false

while getopts ":hal" option; do
  case $option in
    h) echo "usage: $0 [-h] [-a] [-l] file ..."; exit ;;
    a) all=true ;;
    l) long=true ;;
    ?) echo "error: option -$OPTARG is not implemented"; exit ;;
  esac
done

# remove the options from the positional parameters
shift $(( OPTIND - 1 ))

ls_opts=()
$all && ls_opts+=( -a )
$long && ls_opts+=( -l )

# now, do it
ls "${ls_opts[@]}" "$@"

おすすめ記事