SIer だけど技術やりたいブログ

細かくて忘れがちなシェルの便利コマンド

linux

細かくて忘れがちなシェルの便利コマンドをメモする。動作確認はbashのみ。

cd -

カレントディレクトリの前にいたディレクトリに移動する。

$ pwd 
/home/kimulla
$ cd /var/log
$ pwd 
/var/log
$ cd -
$ pwd 
/home/kimulla

<Esc .>

前のコマンドの最後の引数を補完する。

$ view /var/log/messages
$ tail -f <Esc .>
<Esc .> をタイプすると/var/log/messagesが補完される

!$や$_でも同じようなことができるが、補完はされない。何が実行されるのかコマンドからは見えない。

$ view /var/log/messages
$ tail -f !$

!コマンド履歴番号

履歴に残っているコマンドを再度実行する。

$ history
1 ls
2 tail -f /var/log/messages
...
$ !1
ls
Desktop    Downloads  Pictures  Templates 
Documents  Music      Public    Videos 

ロビング(*,?,{},[])

*はよく使うけど、{}は知らなかった。

*

0文字以上の任意の文字列。

$ ls
hello1.txt     hello2.txt    hello3.txt    hello4.txt    hello5.txt
goodbye1.txt   goodbye2.txt  goodbye3.txt  goodbye4.txt  goodbye5.txt
$ ls hello*.txt
hello1.txt  hello2.txt  hello3.txt  hello4.txt  hello5.txt

?

任意の1文字。

$ ls
11.txt  12.txt  13.txt  14.txt  15.txt  1.txt  2.txt  3.txt  4.txt  5.txt
$ ls ?.txt
1.txt  2.txt  3.txt  4.txt  5.txt

[]

範囲内の任意の一文字。

$ ls 
a.txt  b.txt  c.txt  d.txt  aa.txt  bb.txt  cc.txt
$ ls [ab].txt
a.txt  b.txt 

{}

{}を展開して文字列を作成してから実行する。
{a..z}で範囲指定、{a,b,c}で文字列指定。

$ touch {1..5}.txt
1.txt  2.txt  3.txt  4.txt  5.txt
$ touch {after,before}.txt
after.txt before.txt

ヒアドキュメント

文字列を標準入力に渡せる。”<<“で終端文字を指定する。

$ ls
$ cat << FIN > hello.txt
> a
> b
> c
> FIN
$ cat hello.txt 
a
b
c

bashをviのキーバインドで操作する

bashrcあたりに以下をセットすると、vi風のキーバインドbashを操作できる。
その代わり<Esc .>が正常に動かない。

set -o vi

vimからシェルを実行する

vimを起動したあとに “r! xxx “を実行すると起動シェルで xxx コマンドが実行できる