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

シェルスクリプト local コマンド

Posted at

シェル関数内でローカル関数を使いたい場合、local コマンドを使う。
もしグローバス変数と同じ変数名を定義する場合、local コマンドで定義するまでは、その変数はグローバル変数として扱われる。

local-example1.sh
i=1
func()
{
  echo $i  # 1
  local i
  i=5
  echo $i  # 5
}
func
echo $i  # 1

local コマンドが使えないシェルも存在するため、シェル関数内でサブシェルを使ってローカル変数を実現したほうが良いかもしれない。

local-example2.sh
i=1
func()
(
  echo $i  # 1
  i=5
  echo $i  # 5
)
func
echo $i  # 1
0
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
0
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?