如何循环shell脚本,使用不同的变量,存储脚本的整个内容与变量,然后运行另一个函数



假设我有一个包含

的脚本test.sh
#!/bin/bash
for var in var1 var2;
do
  for i in `seq 2`; do
    sh test2.sh $var > tmp.sh
    cat tmp.sh;
  done
done

我有另一个脚本test2.sh看起来像这样

#!/bin/bash
echo "I use the variable here $1"
echo "and again here $1"
echo "even a third time here $1"

现在,在我的第一个脚本中,我想做的是传递test2.sh的整个内容与当前的局部变量(即在第六行:sh test2.sh $var > tmp.sh),所以如果我要调用sh test2.sh var1,那么它将返回

I use the variable here var1
and again here var1
even a third time here var1

所以我想把sh test2.sh $var的全部内容传递给一个新的shell文件,但是用参数代替变量。因此输出应该是:

I use the variable here var1
and again here var1
even a third time here var1
I use the variable here var1
and again here var1
even a third time here var1
I use the variable here var2
and again here var2
even a third time here var2
I use the variable here var2
and again here var2
even a third time here var2

因此,我真正想知道的是;我如何通过一个本地参数传递整个shell到一个新的临时shell脚本?我真正想知道的是我如何运行这样的东西:

for var in var1 var2;
do
  for i in `seq 2`; do
  sh (sh test2.sh $var)
  done
done

谢谢。

您可以读取第二个脚本test2.sh的内容,并在test1.sh中执行它,将参数替换为您的变量值,如下所示:

#!/bin/bash
for var in var1 var2;
do
    for i in `seq 2`; do
        # Get the contents of test2 to a variable
        script=$(cat test2.sh)
        # Set the arguments of the script in the variable and execute
        eval "set -- $var; $script"
    done
done

但是,请仔细阅读使用eval的风险,例如:为什么在Bash中应该避免使用eval,我应该使用什么?

最新更新