LoginSignup
251
211

More than 5 years have passed since last update.

シェルスクリプトで関数を利用する

Posted at

関数の定義

シェルスクリプトでは、関数を次のようにして定義します。

#!/bin/bash
function 関数の名前 () {
    処理
}

このとき、functionは省略可能です。

#!/bin/bash
関数の名前 () {
    処理
}

関数の呼び出し

関数の呼び出しは、関数を定義した後に関数の名前を書くだけです。

関数の名前 引数

このとき、関数の名前に続けて、引数を書くことができます。関数内では、通常のシェルスクリプトの引数を処理するのと同じように\$1、\$2、...という形でアクセスできます。

簡単な例

#!/bin/bash
# 関数の定義
say_hello () {
    echo "Hello, world!"
}
# 関数の呼び出し
say_hello

これで"Hello, world!"が出力されます。

引数をとる例

#!/bin/bash
# 関数の定義
say_hello_people () {
    echo "Hello, $1 and $2!"
}
# 関数の呼び出し
say_hello_people taro hanako

これで"Hello, taro and hanako!"が出力されます。

参考

251
211
1

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
251
211