LoginSignup
4
8

「if then else fi」を一行で書く(シェルスクリプト)

Last updated at Posted at 2019-03-21

こんにちは。
シェル(スクリプト)で、if then else fi を一行で書きました。

「if then else fi」

  • 加えて、&& および || を用いて同等なことを行いました1
if command1; then command2; else command3; fi
{ command1; } && { command2; :; } || { command3; }
if [ $? -eq 0 ]; then echo TRUE; else echo FALSE; fi
{ [ $? -eq 0 ]; } && { echo TRUE; :; } || { echo FALSE; }

&& および || を用いた構文について

上記の &&|| を使ったものに関して、

簡素化可能な場合

コマンドグループ(グルーピング)2 {} は、その中の command が一つの場合には不要です。また command2 の終了ステータスが常に 0 (成功)ならば、: コマンドも省略できます。

  • 下記がその例です
[ $? -eq 0 ] && echo TRUE || echo FALSE
shellcheck を用いて検査

ただし、shellcheck を用いて検査すると警告が出ました。

$ echo '{ echo "A"; } && { echo "B"; :; } || { echo "C"; }' | shellcheck -s sh -
 
In - line 1:
{ echo "A"; } && { echo "B"; :; } || { echo "C"; }
              ^-- SC2015: Note that A && B || C is not if-then-else. C may run when A is true.

For more information:
  https://www.shellcheck.net/wiki/SC2015 -- Note that A && B || C is not if-t...

「while ... do 〜 done」 、「for ... do 〜 done」

「while ... do 〜 done」 、「for ... do 〜 done」 を一行で書くと、

printf 'a\nb\n' | while read -r line; do echo $line; done
for i in 1 2 3; do echo $i; done

「case in esac」

「case in esac」を一行で書く場合は、そのまま率直です。

case "$var" in a*|"") my_func "$var" ;; esac

関数

関数を一行で書く場合も、そのまま率直です3

hello() { echo "Hello, $1."; }
  1. 参考:「便利だが理解を要する制御演算子 &&||

  2. コマンドグループ {} (brace) 内は末尾の ; および開始終了位置の空白(blank space)が必要です。したがって最小例は { :; } となります(もしも { } のように何もコマンドを入れない場合はエラーとなります)。

  3. 一行で書く場合でも、コマンドグループ {} を用いる必要があります。

4
8
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
4
8