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

シェルスクリプトで関数から文字列を返すような機能を模倣する

Last updated at Posted at 2022-03-05

シェルスクリプトで、関数の返り値をreturnで返す場合、文字列を返すとエラーになる

test.sh
#!/bin/bash
function GET_COMMAND(){
    ARG1=${1}
    str="command_${ARG1}"
    return ${str}
}

CMD=`GET_COMMAND 1`
echo ${CMD}
CMD=`GET_COMMAND 2`
echo ${CMD}
$ bash test.sh
test.sh: line 6: return: command_1: numeric argument required
test.sh: line 6: return: command_2: numeric argument required

関数の返り値をechoで返すと返せる(これで良いのか?という疑問は残る。。)

コメント欄のご指摘を受けて表現を取り消しました。誤解を招くような記載ですみません。
「他のプログラミング言語での return のような機能を模倣するために、関数名 や $(関数名) によるコマンド置換 ( 出力のキャプチャ ) を利用する」

以下のようにすることで、returnで文字列を返すような機能を模倣する。

test.sh
#!/bin/bash                                                                     
function GET_COMMAND(){
    ARG1=${1}
    str="command_${ARG1}"
    echo ${str}
}

CMD=`GET_COMMAND 1`
echo ${CMD}
CMD=`GET_COMMAND 2`
echo ${CMD}
$ bash test.sh
command_1
command_2

ファイルを分けたければ、別ファイル(例えば、common.sh)に記述してsource等で読み込んでおくと良い。

https://atmarkit.itmedia.co.jp/ait/articles/1712/21/news015.html

common.sh
#!/bin/bash

function GET_COMMAND(){
    ARG1=${1}
    str="command_${ARG1}"
    echo ${str}
}
test.sh
#!/bin/bash                                                                     

source common.sh      # common.shを呼び出す

CMD=`GET_COMMAND 1`
echo ${CMD}
CMD=`GET_COMMAND 2`
echo ${CMD}
$ bash test.sh
command_1
command_2

以上

参考

1
0
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?