如何避免在此bash函数中使用"for"循环?

neo*_*o33 3 bash

我正在创建这个函数,在文件的每一行上创建多个grep.我运行如下:

cat file.txt | agrep string1 string2 ... stringN 

function agrep () {  
   for a in $@;  do
     cmd+=" | grep '$a'";
   done ;
   while read line ; do
     eval "echo "\'"$line"\'" $cmd";
   done;
}
Run Code Online (Sandbox Code Playgroud)

我们的想法是打印包含所有字符串的每一行:string1,string2,..., stringN.这已经有效,但我想避免使用for构造表达式:

| grep string1 | grep string2 ... | stringN
Run Code Online (Sandbox Code Playgroud)

如果可能,也可以使用eval.我尝试进行如下扩展:

echo "| grep $"{1..3}
Run Code Online (Sandbox Code Playgroud)

我得到:

| grep $1 | grep $2 | grep $3
Run Code Online (Sandbox Code Playgroud)

这几乎是我想要的,但问题是,当我尝试:

echo "| grep $"{1..$#}
Run Code Online (Sandbox Code Playgroud)

由于bash不能扩展,{1..$#}因此不会发生扩展$#.它只适用于数字.我想构建一些有效的扩展,以避免foragrep函数中使用.

rob*_*off 5

agrep () {
    if [ $# = 0 ]; then
        cat
    else
        pattern="$1"
        shift
        grep -e "$pattern" | agrep "$@"
    fi
}
Run Code Online (Sandbox Code Playgroud)