問題:是否存在與Bash的別名替換相當的魚,或者建議最佳做法以保持代碼的清潔和乾燥?別名在魚殼中的替換
背景:在Bash中有一個非常有用的功能叫做別名替換。它在手冊頁中簡要提及:
alias [-p] [name[=value] ...]
...
A trailing space in value causes the next word to be checked for alias substitution when the alias is expanded.
...
此功能的強大功能可以通過示例輕鬆傳達。考慮到許多用戶定義了一個grep別名。這裏是我的:
# extended regex, skip binaries, devices, sockets, & dirs, colored, & line
# -buffered. use a non- canonical alias instead of GREP_OPTIONS which may wreck
# poorly written scripts
alias g='grep -EID skip -d skip --color=auto --line-buffered'
同樣,許多這些相同的用戶爲xargs定義了一個別名。這裏是我的沒有別名替代:
alias x='xargs -rd\\n' # \n delimited, don't run on empty in
最後,這裏就是我可能要使用它,但它不工作:
$ find|x g foo
xargs: g: No such file or directory
,因爲x被擴大到xargs的這個命令失敗,它無法找到名爲g
的可執行文件。這有很多解決方法,但我認爲大多數都很糟糕。然而,僅僅通過增加一個尾部空間,shell將代表我們執行別名替換和該命令將工作打算:
alias x='xargs -rd\\n ' # \n delimited, don't run on empty in, + expansion
# ^-- this space is for expanding a subsequent alias
請記住,這是只是一個例子,不一定是實際用例。
更新2015年5月6日
我從來沒有發現一個Fishism解決辦法,但我覺得選擇是值得評論。我採用了在~/bin
中創建shell腳本的方法。缺點是:
- shell配置現在是多個文件。
- 解釋器失去對其他簡單別名和函數的檢查。
不過,我覺得有利的一面是相當巨大的:
- 腳本可以用任何語言來編寫。
- 腳本完全獨立於shell選項。嘗試新的炮彈是非常痛苦的。擁有一個不需要用多種語言重寫或維護的單個提示腳本是一種樂趣。
第一反應:[no](http://fishshell.com/docs/current/commands.html#alias)。下一個反應:因爲魚別名只是變相的函數,所以你可以創建一個'xg'函數來組合bash'x'和'g'別名。 –
@glennjackman當你說聯合,你的意思是'函數xg; xargs -rd \\ n grep -EID跳過-d跳過--color =自動--line-buffered $ argv; end'?這正是我想要避免的,因爲我需要在'g','xg','x'兩個地方定義''g''''''和'x''函數。 –
這就是我的意思。魚沒有等同於bash的別名替換(或zsh的全局別名),所以我認爲你沒有太多的選擇。我想你可以說類似'function x; xargs -rd \\ n fish -c「$ argv」;結束「,但這可能充滿了陷阱 –