用通配符和大括號實現的shell globbing 的便利功能
當調用腳本的時候,你可能會輸入一些類似的,同質的選項。正好Bash有一些技巧可以擴展文件的後綴名,叫做shell globbing,中文我也暫時不知道怎麼翻譯。
- 通配符(Wildcards ). 做通配符匹配的時候,我們可以使用
?
或者*
。問號?
只匹配一個字符,星號*
可以匹配任意個字符。比如有這樣幾個文件:foo, foo1, foo2, foo10 以及 bar,命令rm foo?
將會刪除foo1和foo2,而rm foo*
將會刪除除了bar以外所有的文件。 - 大括號(
{}
). 當一些類似的命令裏裏有一些字符串,他們雖然不一樣,但是比較類似,就可以用大括號來做一些處理。
看看下面的例子:
convert image.{png,jpg}
# Will expand to
convert image.png image.jpg
cp /path/to/project/{foo,bar,baz}.sh /newpath
# Will expand to
cp /path/to/project/foo.sh /path/to/project/bar.sh /path/to/project/baz.sh /newpath
# Globbing techniques can also be combined
mv *{.py,.sh} folder
# Will move all *.py and *.sh files
mkdir foo bar
# This creates files foo/a, foo/b, ... foo/h, bar/a, bar/b, ... bar/h
touch {foo,bar}/{a..h}
touch foo/x bar/y
# Show differences between files in foo and bar
diff <(ls foo) <(ls bar)
# Outputs
# < x
# ---
# > y
編寫Bash腳本是一件非常反直覺的事情,因此有個工具shell check可以像編譯器那樣檢查你的腳本寫的是否有問題。