理科系の勉強日記

Linux/Ubuntu/Mac/Emacs/Computer vision/Robotics

bashの関数とか

忘れないうちにメモ.

bashの関数作成

$ function plus() {echo $(($1 + $2));}
$ plus 2 3

5

functionの後に上記のように書くことで関数を定義できる.


main関数の返り値

$ grep ll.dat < ll.dat || echo "not found."
-rw-r--r--   1 hogehoge  staff        0  6 27 14:58 ll.dat

$ grep hoge.dat < ll.dat || echo "not found."
not found.

grepやcatなどのコマンドは成功すれば1を返し,処理が失敗すれば0を返す.そこでandやorと組み合わせることでエラーの場合の処理することができる.
( 0なら右を実行 => || , 1なら右を実行 => && )


while read

$ cat ll.dat | while read a b c d e f
>do
>echo "$a and $d"
>done

total and 
-rw-r--r-- and staff
drwx------@ and staff
lrwxr-xr-x and staff
drwxr-xr-x+ and staff
-rw-r--r-- and staff
…

ll.datを毎行読み込んで,$a $b $c…に各要素を格納し,echoでそれらを表示している.ll.datの行数は全部で9あるのだが,変数は$aから$fの6個しか指定していない.この場合あまりの行はすべて$fに格納されることになる.

$ cat ll.dat | while read a b c d e f
>do
>echo "$f"
>done


6 27 14:55 #blog_draft#
6 27 14:58 .
6 27 14:54 .#blog_draft -> hogehoge@Kenta.local.3847
6 27 13:06 ..
6 26 12:35 .DS_Store
...