shellcheckでクセを直そう(bash文法チェック)

シェルスクリプトは、自由度が高く大変便利なものですが、自分のクセで良くない使い方をしてしまっていたりします。それらの間違いを指摘してくれる便利なツール(shellcheck)で、悪いクセを直しましょう。

環境

$ cat /etc/almalinux-release 
AlmaLinux release 9.5 (Teal Serval)
$ uname -r
5.14.0-503.23.1.el9_5.x86_64

shellcheckのインストール

shellcheckはEPELパッケージからインストールをすることができます。EPELの利用に問題がなければEPEPLリポジトリーをインストールしてください。

$ dnf --enablerepo=epel info shellcheck
Last metadata expiration check: 0:02:39 ago on Sun Apr 27 12:01:31 2025.
Available Packages
Name         : ShellCheck
Version      : 0.10.0
Release      : 3.el9
Architecture : x86_64
Size         : 2.6 M
Source       : ShellCheck-0.10.0-3.el9.src.rpm
Repository   : epel
Summary      : Shell script analysis tool
URL          : https://www.shellcheck.net/
License      : GPL-3.0-or-later
   : (省略)
$ dnf --enablerepo=epel install shellcheck
   : (省略)
Installed:
  ShellCheck-0.10.0-3.el9.x86_64

Complete!

使ってみる

使い方は簡単です。

良くない書き方のシェルスクリプト

$ vi test.bash
#!/bin/bash
COUNT=1
while [ "${COUNT}" -le 3 ] ; do
  echo "${COUNT}"
  COUNT=$(expr "${COUNT}" + 1)
done

$ chmod 755 test.bash
$ ./test.bash ・・・ 実行すると正常に動作する
1
2
3

shellcheckをしてみると、
「exprは古くなっています。$((..))、${}、または[[ ]]を使用して書き直すことを検討してください」とのこと。

$ shellcheck test.bash

In test.bash line 6:
  COUNT=$(expr "${COUNT}" + 1)
          ^--^ SC2003 (style): expr is antiquated. Consider rewriting this using $((..)), ${} or [[ ]].

For more information:
  https://www.shellcheck.net/wiki/SC2003 -- expr is antiquated. Consider rewr...

良い書き方のシェルスクリプト

shellcheckの指摘に従い、シェルスクリプトの書き方を変えてみます。

$ vi test.bash
#!/bin/bash
COUNT=1
while [ "${COUNT}" -le 3 ] ; do
  echo "${COUNT}"
  COUNT=$(("${COUNT}" + 1))
done

$ ./test.bash ・・・ 実行結果は同じ
1
2
3

もう一度、shellcheckをしてみると、何も指摘をされません。

$ shellcheck test.bash
タイトルとURLをコピーしました