繁体   English   中英

如何循环使用具有不同变量的Shell脚本,使用变量存储脚本的全部内容,然后运行另一个函数

[英]How to loop over shell script, with different variable, store entire contents of script with variable, and then run another function

假设我有一个包含以下内容的脚本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

因此,我真正想知道的是; 如何将带有局部参数的整个外壳传递给新的临时外壳脚本? 我真正想知道的是如何运行这样的内容:

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

谢谢。

您可以读取第二个脚本test2.sh的内容,并在test1.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, 我应该使用什么代替?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM