2012-06-09 44 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