在循环结束后使用 for 循环中的变量
Using variables from for loop after loop has closed
我已经删除了旧问题,希望这个简化和更精确的版本能起作用。
我有一个文件:
#Works Command
cd /tmp
mkdir folder
echo "it worked" >file
cat file
#Not working Command
cd /tmp
mkdir file
echo "it didn't work" >wrong
cat wrong
命令可以少至 1 组,多至 20 组,但每组命令都带有以 "Command"
结尾的注释前缀
我希望完成的是将每个评论设置为一个变量,调用时将执行命令。
如果我回显 $var1
就会得到想要的结果
cd /tmp
mkdir folder
echo "it worked" >file
cat file
我试过使用:
while read -r line; do var+=("$line"); done < <(awk '/Command/,/Command/' file)
要给变量设置注释,但是我还没有找到可行的命令分组方案。
我试过使用:
for i in {1..5}
do
awk '/'"${var[$i]}"'/,/'"${var[$i+1]}"'/' file |egrep -vi "${var[$i]}|${var[$i+1]}"
done
希望这有助于澄清事情。我很抱歉在没有明确希望需要做什么的情况下发布问题。
你更新的问题听起来像是你需要非常小心的事情,但在这里你开始(我改变了示例输入,因为我不想在 /tmp
中创建文件!) :
$ cat file
#First Command
echo 'here is the date'
date +'%D'
#Second Command
echo 'here is the time'
date +'%T'
$ IFS=$'\n' var=( $(awk -v RS= -v FS='\n' -v OFS=';' '{for (i=2;i<=NF;i++) printf "%s%s", $i, (i<NF?OFS:ORS)}' file) )
$ echo "${var[0]}"
echo 'here is the date';date +'%D'
$ echo "${var[1]}"
echo 'here is the time';date +'%T'
$ eval "${var[0]}"
here is the date
05/07/15
$ eval "${var[1]}"
here is the time
11:42:51
您可以决定 eval
或 declare
或其他方式是否是执行命令的正确方式。
我已经删除了旧问题,希望这个简化和更精确的版本能起作用。
我有一个文件:
#Works Command
cd /tmp
mkdir folder
echo "it worked" >file
cat file
#Not working Command
cd /tmp
mkdir file
echo "it didn't work" >wrong
cat wrong
命令可以少至 1 组,多至 20 组,但每组命令都带有以 "Command"
结尾的注释前缀我希望完成的是将每个评论设置为一个变量,调用时将执行命令。
如果我回显 $var1
就会得到想要的结果cd /tmp
mkdir folder
echo "it worked" >file
cat file
我试过使用:
while read -r line; do var+=("$line"); done < <(awk '/Command/,/Command/' file)
要给变量设置注释,但是我还没有找到可行的命令分组方案。
我试过使用:
for i in {1..5}
do
awk '/'"${var[$i]}"'/,/'"${var[$i+1]}"'/' file |egrep -vi "${var[$i]}|${var[$i+1]}"
done
希望这有助于澄清事情。我很抱歉在没有明确希望需要做什么的情况下发布问题。
你更新的问题听起来像是你需要非常小心的事情,但在这里你开始(我改变了示例输入,因为我不想在 /tmp
中创建文件!) :
$ cat file
#First Command
echo 'here is the date'
date +'%D'
#Second Command
echo 'here is the time'
date +'%T'
$ IFS=$'\n' var=( $(awk -v RS= -v FS='\n' -v OFS=';' '{for (i=2;i<=NF;i++) printf "%s%s", $i, (i<NF?OFS:ORS)}' file) )
$ echo "${var[0]}"
echo 'here is the date';date +'%D'
$ echo "${var[1]}"
echo 'here is the time';date +'%T'
$ eval "${var[0]}"
here is the date
05/07/15
$ eval "${var[1]}"
here is the time
11:42:51
您可以决定 eval
或 declare
或其他方式是否是执行命令的正确方式。