test.shの引数を以下3パターン検討しているのですが
その場合のエラーハンドリングで愚直な方法は思う浮かんだとですが
他にきれいな記載方法あれば教えていただきたいです。
- -a は引数なしで動作
- -b は第一引数のみ (オプションが-bの場合は、第一引数があるかチェック)
- -c は第一、第二引数 (オプションが-cの場合は、第一引数 or 第二引数があるかチェック)
$ ./test.sh -a $ ./test.sh -b "b" $ ./test.sh -c "c" "cc"
#!/bin/bash first=$1 second=$2 third=$3 if [ $first=="-a" ]; then echo OK if [ $first == "-b" ]; then if [ -z $second ]; then echo -b引数エラー exit 250 fi elif [ $first == "-c" ]; then if [ -z $second ] || [ -z $third ]; then echo どちらか不足 second : $second third : $third exit 250 fi fi else echo オプションエラー fi while getopts ab:c: OPT do case $OPT in a) echo "-a " ;; b) echo "-b = ${OPTARG}" ;; c) echo "-c = ${OPTARG}" ;; esac done

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。