0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[WIP] dash で set -u しても未定義変数エラーにならない

Posted at

メモ

どうでもいいスクリプトを組んでいたらつまらないバグを作りこんでいて、その時気が付いたのですが dash では set -u しているのになぜか未定義変数でエラーになりませんでした。
とりあえずメモ。

環境

  • Ubuntu 22.04.5 LTS (実際には WSL)
  • dash 0.5.11+git20210903+057cd650a4ed-3build1

事象

シェルスクリプトで計算をしているところで、結果がおかしくなっていました。
原因は、単に変数名を打ち間違えていただけなのですが set -u をしていたのに、エラーになりませんでした。

概念的には下記のようなスクリプトで y が未定義だった状況です(実際の変数名や計算式は違いますが)。

result=$(( x + y - 1))

ubuntu 上で #!/bin/sh としていたので、dash で動かしていました。

再現

以下のようにset -u をしていても $(( x )) で未定義変数を使うと、dash ではエラーにならず 0 として扱われるようです。
$(( $x )) ではエラーになります(x: parameter not set)。

bash ではどちらもエラーになるようです(x: unbound variable)。

$ cat a.sh
#!/bin/dash
set -u

echo 'echo $(( x ))'
echo $(( x ))

echo 'echo $(( $x ))'
echo $(( $x ))

$ ./a.sh
echo $(( x ))
0
echo $(( $x ))
./a.sh: 8: x: parameter not set
exited 2
$ dash a.sh
echo $(( x ))
0
echo $(( $x ))
a.sh: 8: x: parameter not set
exited 2
$ /bin/sh a.sh
echo $(( x ))
0
echo $(( $x ))
a.sh: 8: x: parameter not set
exited 2
$ bash a.sh
echo $(( x ))
a.sh: line 5: x: unbound variable
exited 1
$

exited 1 とか出ているのは終了コードを出すようにしているだけなので、気にしないでください。

仕様

dash の仕様通りなのか、バグなのかよくわからないですけど、とりあえずメモ。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?