RHEL9 シェルスクリプト getopsでオプションを受け取って処理を行う

環境
Red Hat Enterprise Linux release 9.2 (Plow)

構文
while getopts a:b:c: OPT
do
処理コード
done
getopsコマンドを使ってオプションを受け取って処理を行います

サンプルコード(data.sh)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
#!/bin/bash
while getopts a:b:c: OPT
do
case "$OPT" in
a)echo "a = ${OPTARG}";;
b)echo "b = ${OPTARG}";;
c)echo "c = ${OPTARG}";;
esac
done
#!/bin/bash while getopts a:b:c: OPT do case "$OPT" in a)echo "a = ${OPTARG}";; b)echo "b = ${OPTARG}";; c)echo "c = ${OPTARG}";; esac done
#!/bin/bash
while getopts a:b:c: OPT
do
  case "$OPT" in
    a)echo "a = ${OPTARG}";;
    b)echo "b = ${OPTARG}";;
    c)echo "c = ${OPTARG}";;
  esac
done

getoptsはコマンドです。
以下のようにオプション(a,b,c)と引数を指定して実行できます。

./data.sh -a 22 -c 44
./data.sh -a 22 -b 44 -c 33

IT

Posted by arkgame