シェルスクリプトの変数名は先頭文字に数字を使えない

UNIX3-100

シェルスクリプトで定義する変数名には、ルールがあります。

※ 数字を先頭にした変数名は利用できません。

数字を先頭にした変数名を使用すると、以下のエラーが発生します。

・日本語表示
1HENSU=AAA BBB: コマンドが見つかりません
${1HENSU}: 悪い代理

・英語表示
1HENSU=AAA BBB: command not found
${1HENSU}: bad substitution

 

実際にテストしてみます。



 

失敗するパターン

数字から始まる変数名を使った例です。変数名は「1HENSU」です。
実行してみると、「コマンドが見つかりません」と「悪い代理」というエラーになります。

・シェルスクリプト内容

# cat ./test.sh
#!/bin/sh

1HENSU="AAA BBB"

echo ${1HENSU}

#

 ・実行結果

# ./test.sh
./test.sh: line 3: 1HENSU=AAA BBB: コマンドが見つかりません
./test.sh: line 5: ${1HENSU}: 悪い代理
#

・LNG=Cで実行する

英語表示で実行してみると、「command not found」と「bad substitution」というエラーになります。

# LANG=C
# ./test.sh
./test.sh: line 3: 1HENSU=AAA BBB: command not found
./test.sh: line 5: ${1HENSU}: bad substitution
#

 

成功するパターン

変数名を「1HENSU」から「HENSU」に変えて実行してみると、うまく動いてくれます。

・シェルスクリプト内容

# cat ./test.sh
#!/bin/sh

HENSU="AAA BBB"

echo ${HENSU}

#

・実行結果

# ./test.sh
AAA BBB
#

 



 

 


サブコンテンツ

このページの先頭へ


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/luck777er/it-memo.info/public_html/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048