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?

More than 3 years have passed since last update.

shellscriptの関数

Last updated at Posted at 2021-04-12

shellscriptでfunctionを勉強したので、まとめます。

参考記事

書式

func.sh
function 関数名(){
 処理 
}

関数名(){
  処理
}

local

関数の中で変数を扱う。

local.sh
HELLO=aaa
hello(){
  local HELLO=hello
  echo $HELLO  #hello
}
echo $HELLO  #aaa

localを使うことで関数ないでのみ変数を保持する。

戻り値

戻り値が存在しないので変数に格納するなどする。

return.sh
function(){
  echo 'return value'
}

RTN=`function`
echo $RTN

FUNCNAME変数

使う機会はあるかわからないけどhelp functionに載っていたので一応メモ。
自身の関数の名前を格納している変数。

func_name.sh
function_name(){
  echo $FUNCNAME  #function_name
}

readonly

変数や関数をreadonly(上書きできないよう)にする。

変数

ro.sh
var=10
readonly var  # $はつけない
var=20

関数

func_ro.sh
hello(){
  echo 'first Hello'
}

readonly -f hello  #  fオプションを指定しないとそのまま上書きされる

hello(){
  echo 'second Hello'
}

これらを実行すると上書き不可能のエラーが出る。

間違いがございましたら、ご指摘ください。

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?