Linux Shell周りの機能


shell周りの機能についてまとめます。

コマンドの実行制御

複数コマンドを実行するときの実行制御についてです。

コマンド 説明
コマンド1 ; コマンド2 コマンド1に続いてコマンド2を実行する
コマンド1 && コマンド2 コマンド1が正常終了したときのみコマンド2を実行する
コマンド1 || コマンド2 コマンド1が正常終了しなかったときのみコマンド2を実行する
(コマンド1 ; コマンド2) コマンド1とコマンド2をひとまとまりのコマンドとして実行する
$ ls
a.txt  b.txt  c.txt  test  test2
$ cat a.txt
this is a.txt.

$ cat a.txt ; ls
this is a.txt.
a.txt  b.txt  c.txt  test  test2

$ cat a.txt && ls
this is a.txt.
a.txt  b.txt  c.txt  test  test2
# 「cat a.txt」が成功しているので「ls」も実行されている

$ cat a.txt || ls
this is a.txt.
# 「cat a.txt」が成功しているので「ls」は実行されていない

$ cat d.txt && ls
cat: d.txt: No such file or directory
# 「cat d.txt」が失敗しているので「ls」も実行されていない

$ cat d.txt || ls
cat: d.txt: No such file or directory
a.txt  b.txt  c.txt  test  test2
# 「cat d.txt」が失敗しているので「ls」が実行されている

$ (cat a.txt ; ls) > c.txt
$ cat c.txt
this is a.txt.
a.txt
b.txt
c.txt
test
test2

引用句

shell内で引用句を使ったときには、引用句の種類によって挙動が変わる。

引用句 説明
シングルクォーテーション シングルクォーテーションで囲まれた部分はすべて文字列として解釈される。
ダブルクォーテーション ダブルクォーテーションで囲まれた部分はすべて文字列として解釈される。ただし、変数が含まれていればその変数は展開される。
バッククォーテーション バッククォーテーションで囲まれた部分にコマンドがあれば、そのコマンドが実行されて表示される。また、変数があり、その中身がコマンドのときもそのコマンドが実行される。
sample
$ echo $PWD
/root/test

$ echo 'This directory is $PWD' 
This directory is $PWD
# すべて文字列として解釈される

$ echo "This directory is $PWD"
This directory is /root/test
# 変数は展開され、それ以外は文字列として解釈される

$ echo "This directory is `pwd`"
This directory is /root/test
# pwdコマンドが実行されて表示される (全体をシングルクォーテーションで囲むとすべて文字列として認識される)

メタキャラクタ

shell内で使用できるメタキャラクタは以下の通り。

メタキャラクタ 説明
* 0文字以上の文字、文字列にマッチする
? 任意の一文字にマッチする
[] []内の文字のどれかにマッチする
-:連続した範囲を指定できる
!:マッチしない範囲を指定できる
{} ,で区切られた文字列を、ファイル名にマッチするかどうかに関わらず展開する
展開した上で他のメタキャラがあれば、改めてマッチを判断する
\ メタキャラクタのエスケープ
sample
$ ls
a.txt  aaa.txt  b.txt  c.txt  test  test2

$ ls *.txt
a.txt  aaa.txt  b.txt  c.txt

$ ls ?.txt
a.txt  b.txt  c.txt

$  ls [a-c].txt
a.txt  b.txt  c.txt

$ ls {a,aaa}.txt
a.txt  aaa.txt

$ ls {a,d}.txt  # d.txtが存在しなくても展開はされる
ls: cannot access 'd.txt': No such file or directory
a.txt

リダイレクト

コマンドへの入力元や主力先を変更することができる。

入力出力 説明
標準出力先の変更 >
>> 追記
標準入力元の変更 <
ヒアドキュメント << 終了文字
終了文字が入力されるまで入力を続ける
sample
$ ls > log.txt    # ls の結果をlog.txtに書き込む
$ cat log.txt
log.txt
test.txt
test1.txt

$ ls -l >> log.txt    # ls -l の結果をlog.txtに追記する
$ cat log.txt
log.txt
test.txt
test1.txt
total 4
-rw-r--r-- 1 root root 27 Dec 24 06:14 log.txt
-rw-r--r-- 1 root root  0 Dec 23 13:24 test.txt
-rw-r--r-- 1 root root  0 Dec 23 13:24 test1.txt

$ grep "log.txt" < log.txt    # grep コマンドへの入力をlog.txtにする
log.txt
-rw-r--r-- 1 root root 27 Dec 24 06:14 log.txt

$ cat << EOF > test.txt    # EOF という入力があるまで入力を受け付け、結果をtest.txtに書き込む
> aaa
> bbb
> ccc
> EOF
$ cat test.txt
aaa
bbb
ccc