gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:16 24 4
gpt4 key购买 nike

假设我有一个脚本 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 的全部内容与当前局部变量一起传递(即在第 6 行:sh test2.sh $var > tmp.sh) 所以如果我调用 say 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 的风险,例如这里:Why should eval be avoided in Bash, and what should I use instead?

关于linux - 如何使用不同的变量循环 shell 脚本,用变量存储脚本的全部内容,然后运行另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32302714/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com