対話型シェルでbashの一時関数を宣言して使用する

対話型シェルでbashの一時関数を宣言して使用する

基本的には

// declare
const my_func = function(param1, param2) { do_stuff(param1, param2) }
// use
my_func('a', 'b');

ファイルを使用せずに現在の対話型シェル内のすべて

ベストアンサー1

bash関数は、シェルスクリプトと同じ方法で対話型シェルで定義されますbash

あなたの例を出発点として使用してください。

my_func () { do_stuff "$1" "$2"; }

コマンドラインにこれ​​を入力できます。次に呼び出します(コマンドラインでも可能)。

my_func 'something' 'something else' 'a third thing'

ちなみに、CやC ++などの言語のようにパラメータリストを宣言する必要はありません。インテリジェントに取得された引数を使用することは関数に依存します(そして後でより深刻な作業に使用されるかどうかは、関数の使用を文書化することもユーザーによって異なります)。

これは、do_stuff私が渡した3つのパラメータのうち最初のパラメータとして呼び出されますmy_func

何かをする関数少しより興味深い:

countnames () (
    shopt -s nullglob
    names=( ./* )
    printf 'There are %d visible names in this directory\n' "${#names[@]}"
)

インタラクティブシェルに入力するのを防ぐことはできませんbash。これにより、countnames現在のシェルセッションでシェル機能を使用できるようになります。 (関数本体をサブシェル()に書き込んでいることに注意してください。呼び出しシェルで設定されているシェルオプションに影響を与えずにシェルオプションを設定したいので、これを(...)行います。配列は自動的にローカルにローカル配列になります。nullglobnames

テスト:

$ countnames
There are 0 visible names in this directory
$ touch file{1..32}
$ ls
file1  file12 file15 file18 file20 file23 file26 file29 file31 file5  file8
file10 file13 file16 file19 file21 file24 file27 file3  file32 file6  file9
file11 file14 file17 file2  file22 file25 file28 file30 file4  file7
$ countnames
There are 32 visible names in this directory

または、zshこの機能のより洗練されたヘルパーとしてシェルを使用してください。

countnames () {
    printf 'There are %d visible names in this directory\n' \
        "$(zsh -c 'set -- ./*(N); print $#')"
}

関数を「定義解除」(削除)するには、以下を使用しますunset -f

$ countnames
There are 3 visible names in this directory
$ unset -f countnames
$ countnames
bash: countnames: command not found

おすすめ記事