【问题标题】:How to pass parameter to a bash function from shell如何从shell将参数传递给bash函数
【发布时间】:2011-11-18 07:09:36
【问题描述】:

我在.bash_aliases中定义了以下函数

findphp () {
    find -name '*.php' -exec grep -H  --color "$@" "{}" \;
}

它允许我运行 findphp 'function x' 之类的东西来查找 php 文件中对 function x 的所有引用

现在我想将文件类型传递给搜索,例如js,css,ctp作为bash中的参数

我定义了以下函数并获取了 .bash_aliases

myfind () {
    find -name '*.$1' -exec grep -H  --color "$2" "{}" \;
}

但它不起作用,我尝试了单引号,位置参数周围的双引号 无济于事。

如何定义一个函数,将文件扩展名和搜索字符串作为命令行参数?

【问题讨论】:

    标签: bash shell parameter-passing


    【解决方案1】:

    单引号可防止变量扩展。使用"*.$1"

    【讨论】:

      【解决方案2】:

      试试这个:

      findphp () {
          find . -name "*.$1" -exec grep -H --color "${@:2}" "{}" \;
      }
      

      findphp () {
          find . -name "*.$1" -print0 | xargs -0 grep -H --color "${@:2}"
      }
      

      如果你也想要文件名

      【讨论】:

        猜你喜欢
        • 2021-10-05
        • 2019-12-26
        • 2018-05-22
        • 2012-04-21
        • 2017-06-03
        • 2011-12-26
        • 2019-09-29
        • 2015-10-05
        相关资源
        最近更新 更多