関数の使い方
参考:
Create and Use Bash Functions | Like Geeks
What’s the use of parentheses `()` in shell function definition? – Ask Ubuntu
引数を渡す
参考:
bash の引数 (関数の引数・位置パラメータ) についてのまとめ | それマグで!
Pass arguments into a function – Linux Shell Scripting Tutorial | A Beginner’s handbook
How to pass parameters to function in a bash script? – Unix & Linux Stack Exchange
Passing parameters to a Bash function – Stack Overflow
引数の数
$ function count () { \ echo "$#"; \ } $ count "foo" "bar" "baz" 3
参考:
Find Number Of Arguments Passed | nixCraft
配列を渡す
参考:
Passing Array to Function in Bash shell – nixCraft Linux/Unix Forum
How to pass an array as function argument? – Ask Ubuntu
参照渡し
渡された外部の変数を書き換えることができる。
$ function say () \ { \ local -n ref=$1; \ ref="bye"; \ } $ greeting="hello" $ echo $greeting hello $ say greeting $ echo $greeting bye
参考:
Passing arguments by reference – Stack Overflow
call-by-reference
参考:
How to use call-by-reference on an argument in a bash function – Unix & Linux Stack Exchange
Bash expand variable in a variable – Stack Overflow
子プロセスに引き継ぐ (export)
指定した関数を export -f
コマンドで子プロセスとして起動するシェルに引き継げるようになる。
$ export -f hoge
xargs
で関数を使用する場合は、export
した上で bash -c
コマンドを使用する。
$ ls | xargs bash -c hoge
参考:
xargs で function を呼び出す話。- Qiita
xargs に bash の function を渡す方法 | wrist blog
Can I “export” functions in bash? – Unix & Linux Stack Exchange
エイリアスと関数の使い分け
参考: