4
1

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.

set -uを指定したシェルスクリプトで未指定を許容する

Last updated at Posted at 2020-01-02

set-uオプションを指定しておくと、未指定のまま変数を使うのを避けられるので便利です。
ただ、以下のように明示的にエラーメッセージを出したい場合もあります。

test.sh
#!/bin/bash
set -u

if [[ -z "$1" ]]; then
  echo "no arg" >&2
  echo "Usage: ..."
  exit 1
fi

# 省略...

しかし、-uが適用されるため自前でのチェックができません。

bash-3.2$ ./test.sh 
./test.sh: line 4: $1: unbound variable

次のように一時的に無効にすれば対応できますが、コードの状態が増えるし、戻し忘れのリスクもあります。

#!/bin/bash
set -u

set +u # 一時的にuオプションを無効にする
if [[ -z "$1" ]]; then
  # 省略...
fi
set -u # 戻す

では、どうするか?
デフォルト値を利用することで、-uオプションのチェックを回避することができます。
Man page of BASH

${parameter:-word}
デフォルトの値を使います。 parameter が設定されていないか空文字列であれば、 word を展開したものに置換されます。そうでなければ、 parameter の値に置換されます。

wordを指定しなければデフォルトに空文字が入るため、自前で空文字チェックができます。

#!/bin/bash
set -u

if [[ -z "${1:-}" ]]; then
  # 省略...
fi

結果

bash-3.2$ ./test.sh 
no arg
Usage: ...

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?