53
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

シェルスクリプトでオプション付きのコマンドを作成する

Last updated at Posted at 2019-03-09

概要

シェルスクリプトでオプション付きのコマンドを作成する方法。

関連記事

シェルスクリプトを作成

sampleという名前でファイルを作成する

$ vi sample

シェルスクリプトを作成

sample
#!/bin/bash
# helpを作成
function usage {
  cat <<EOM
Usage: $(basename "$0") [OPTION]...
  -h          Display help
  -a VALUE    A explanation for arg called a
  -b VALUE    A explanation for arg called b
  -c VALUE    A explanation for arg called c
  -d VALUE    A explanation for arg called d
EOM

  exit 2
}

# 引数別の処理定義
while getopts ":a:b:c:d:h" optKey; do
  case "$optKey" in
    a)
      echo "-a = ${OPTARG}"
      ;;
    b)
      echo "-b = ${OPTARG}"
      ;;
    c)
      echo "-c = ${OPTARG}"
      ;;
    d)
      echo "-d = ${OPTARG}"
      ;;
    '-h'|'--help'|* )
      usage
      ;;
  esac
done

実行権限を付与

$ chmod u+x sample

実行例

$ ./sample -a sample001
-a = sample001

$ ./sample -b sample002
-b = sample002

$ ./sample -c sample003
-c = sample003

$ ./sample -d sample004
-d = sample004

$ ./sample -a sample001 -b sample002 -c sample003 -d sample004
-a = sample001
-b = sample002
-c = sample003
-d = sample004

$ ./sample -d sample004 -a sample001 -c sample003
-d = sample004
-a = sample001
-c = sample003

-hもしくは、存在しないオプションを付与した場合は、helpが表示される。

$ ./sample -h
Usage: sample [OPTION]...
  -h          display help
  -a VALUE    a explanation for arg called a
  -b VALUE    a explanation for arg called b
  -c VALUE    a explanation for arg called c
  -d VALUE    a explanation for arg called d

$ ./sample -z sample999
Usage: sample [OPTION]...
  -h          display help
  -a VALUE    a explanation for arg called a
  -b VALUE    a explanation for arg called b
  -c VALUE    a explanation for arg called c
  -d VALUE    a explanation for arg called d

パスワードプロンプト

sample.sh
#!/bin/bash
# 入力時に表示される
read -p "username: " USERNAME
echo $USERNAME

# 入力時に表示されない
read -sp "Password: " PASSWORD
echo 
# 入力した文字列を表示
echo $PASSWORD

実行

$ bash sample.sh
username: my_user
my_user # 入力した文字列
Password: ### 入力する ###
my_pasword # 入力した文字列
53
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
53
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?