Help us understand the problem. What is going on with this article?

シェルスクリプト 引数解析のテンプレート

More than 3 years have passed since last update.

書くたびにググるルーチンが3回目を超えたのでメモ。

bash によるオプション解析@b4b4r07 を自分向けに簡潔にまとめたものです。
while の条件式や argv への push だけチョロっと変更してます。

#!/bin/bash

declare -i argc=0
declare -a argv=()

flag_help=false
# flag_foo=false

while [[ $# -gt 0 ]]
do
  case "$1" in
    # long opts supplied '--help'
    --help)
      flag_help=true
      shift
      ;;

    # long opts supplied '--foo'
    # --foo)
    #   flag_foo=true
    #   shift
    #   ;;

    -*)
      # short opts contains 'h' flag
      if [[ "$1" =~ h ]]; then
        flag_help=true
      fi

      # short opts contains 'b' flag
      # if [[ "$1" =~ b ]]; then
      #   flag_b=true
      # fi
      # ...

      shift
      ;;

    *)
      # push argv
      ((++argc))
      argv+=("$1")
      shift
      ;;
  esac
done

# if ($flag_hel); then
#   echo "Usage: $(basename $0) ARG1 ARG2" 1>&2
#   exit 1
# fi

# if !($flag_foo); then
#   ...
# fi

# if [[ $argc -lt 2 ]]; then
#   echo "MUST specify 2 arguments." 1>&2
#   exit 1
# fi

# echo "arg1 : $argv[0]"
# echo "arg2 : $argv[1]"
# echo "args : $argv[@]"

# more scripts...
  • 実引数の数は $argc, 値は $argv[0], $argv[1] ... で参照
  • オプションは [[ $flag_XXX ]] で検査

bash でのみ検証済み。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away