1
0

More than 3 years have passed since last update.

シェルスクリプト シェル関数内変数

Posted at
グループコマンド {} で関数を定義した場合、グローバル変数のように扱われる
shell-func-variable1.sh
VAL="A"
echo "1:${VAL}"
func()
{
  VAL="B"
  echo "2:${VAL}"
}
func

echo "3:${VAL}"
shell-func-variable-result1.sh
$ ./shell-func-variable1.sh
1:A
2:B
3:B
サブシェル () を使って関数を定義した場合、ローカル変数のように扱われる
shell-func-variable2.sh
VAL="A"
echo "1:${VAL}"
func()
(
  VAL="B"
  echo "2:${VAL}"
)
func

echo "3:${VAL}"
shell-func-variable-result2.sh
$ ./shell-func-variable1.sh
1:A
2:B
3:A
local コマンドを使って、ローカル変数をつかう。
shell-func-variable3.sh
VAL="A"
echo "1:${VAL}"
func()
{
  local VAL="B"
  echo "2:${VAL}"
}
func

echo "3:${VAL}"
shell-func-variable-result3.sh
$ ./shell-func-variable1.sh
1:A
2:B
3:A
1
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
1
0