Bash

bashrc 懶惰替換

  • May 13, 2017

如何在執行時~/.bashrc獲取別名來**評估$()**替換,而不是在 ~/.bashrc 執行時(打開終端時)?

我經常執行這個命令,以至於我想為它添加一個別名:

svn diff -r $(svn info | grep ^Revision | awk {'print $2'}):HEAD $(svn info | grep ^URL | awk {'print $2'}) | colordiff

但是,當我將其添加~/.bashrc為別名時,我看到評估被硬編碼為我打開終端時的值:

$ alias
alias svnbranch='svn diff -r 178184:HEAD svn+ssh://branches/t4252 | colordiff'

如果我在其中打開終端,~則會出現錯誤:

svn: E155007: '/home/dotancohen' is not a working copy
svn: E155007: '/home/dotancohen' is not a working copy
svn: E155007: '/home/dotancohen' is not a working copy
svn: E155007: '/home/dotancohen' is not a working copy
$ alias
alias svnbranch='svn diff -r :HEAD  | colordiff'
$

我已經嘗試了別名的這兩種變體~/.bashrc,它們都具有相同的效果(如我所料):

alias svnbranch="svn diff -r $(svn info | grep ^Revision | awk {'print $2'}):HEAD $(svn info | grep ^URL | awk {'print $2'}) | colordiff"
alias svnbranch="svn diff -r `svn info | grep ^Revision | awk {'print $2'}`:HEAD `svn info | grep ^URL | awk {'print $2'}` | colordiff"

**如何在執行時獲得~/.bashrc別名來評估$()**替換?

此外,如何**在 Google 中搜尋這種情況?**我試過用Google搜尋“bashrc 替換”、“bashrc 惰性替換”和其他關鍵片語,但我沒有找到任何我認為應該是一個足夠常見的問題來查找資訊的問題。

使用單引號來抑制特殊字元的處理。您也可以反斜杠s$

對於一個複雜的命令,在任何情況下你最好使用一個函式,它不需要任何轉義並且更容易閱讀和編輯:

svnbranch() {
   svn diff -r $(svn info | grep ^Revision | awk {'print $2'}):HEAD $(svn info | grep ^URL | awk {'print $2'}) | colordiff
}

您可以在任何可以定義別名的地方定義函式。

引用自:https://unix.stackexchange.com/questions/199085