2012-06-09 45 views
0

我想用幾個參數使用bash別名和bash函數。我模擬svn子命令。帶有幾個參數的Bash別名和bash函數

$ svngrep -nr 'Foo' . 
$ svn grep -nr 'Foo' . 

我的期望是既充當如下:

grep --exclude='*.svn-*' --exclude='entries' -nr 'Foo' . 

但實際中,只有別名( 'svngrep')做得很好,功能( 'SVN的grep')導致無效的選項錯誤。如何寫我的.bashrc?

#~/.bashrc 

alias svngrep="grep --exclude='*.svn-*' --exclude='entries'" 

svn() { 
    if [[ $1 == grep ]] 
then 
    local remains=$(echo [email protected] | sed -e 's/grep//') 
    command "$svngrep $remains" 
else 
    command svn "[email protected]" 
fi 
} 

回答

2

你想shift從位置參數去掉第一個字:這樣可以保留的"[email protected]"陣列狀的性質。

svn() { 
    if [[ $1 = grep ]]; then 
    shift 
    svngrep "[email protected]" 
    else 
    command svn "[email protected]" 
    fi 
} 

使用bash的[[內置單=用於字符串平等和雙==用於模式匹配 - 你只需要前者在這種情況下。

0

svngrep不是一個變量。這是bash使用的別名。因此,必須建立像一個新的變量:

svngrep_var="grep --exclude='*.svn-*' --exclude='entries'" 

而在你的程式碼中使用它:

... 
command "$svngrep_var $remains" 
... 
0

我重新因子這個由我自己。並且工作正常!謝謝!

#~/.bashrc 
alias svngrep="svn grep" 
svn() { 
if [[ $1 == grep ]] 
then 
    local remains=$(echo $* | sed -e 's/grep//') 
    command grep --exclude='*.svn-*' --exclude='entries' $remains 
else 
    command svn $* 
fi 
} 

我選擇我保持別名簡單。我使用$ *而不是$ @。

編輯:2012-06-11

#~/.bashrc 
alias svngrep="svn grep" 
svn() { 
    if [[ $1 = grep ]] 
    then 
    shift 
    command grep --exclude='*.svn-*' --exclude='entries' "[email protected]" 
    else 
    command svn "[email protected]" 
    fi 
} 
+1

請參閱[BashFAQ/050](http://mywiki.wooledge.org/BashFAQ/050),[Quotes](http://mywiki.wooledge.org/Quotes)和[Special Parameters](http: //mywiki.wooledge.org/BashSheet#Special_Parameters)。 –

+0

這將非常脆弱;請閱讀丹尼斯的鏈接,然後使用@ glenn的解決方案。 –

+0

謝謝,我理解$ *和$ @之間的推論。我必須使用雙倍$ @,如「$ @」。 – sanemat