以编程方式将glob添加到bash命令

ehi*_*ime 1 bash glob

如果我在bash脚本中没有满足我的参数,那么寻找一种扩展glob的方法,我不是积极的,但我认为它可能需要eval或类似的东西,但我不记得了我的头.

功能

function search ()
{
  [ 'x' == "${2}x" ] && {
    what="*"
  } || {
    what="${2}"
  }

  grep -n -Iir "${1}" "${what}"
}
Run Code Online (Sandbox Code Playgroud)

没有arg2的预期结果

grep -n -Iir 'something' *  ## ran as the normal command
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 5

请记住,a *grep启动之前会被shell扩展为文件名列表.因此,您可以自己扩展它们:

search() {
  local tgt=$1; shift      # move first argument into local variable tgt
  (( "$#" )) || set -- *   # if no other arguments exist, replace the remaining argument
                           # ...list with filenames in the current directory.
  grep -n -Iir "$tgt" "$@" # pass full list of arguments through to grep
}
Run Code Online (Sandbox Code Playgroud)