为什么我在do循环中设置的变量消失了?(unix壳) [英] Why does my variable set in a do loop disappear? (unix shell)

查看:56
本文介绍了为什么我在do循环中设置的变量消失了?(unix壳)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的脚本的这一部分正在比较文件的每一行以查找预设的字符串.如果该字符串在文件中不作为一行存在,则应将其附加到文件末尾.

This part of my script is comparing each line of a file to find a preset string. If the string does NOT exist as a line in the file, it should append it to the end of the file.

STRING=foobar
cat "$FILE" | while read LINE
    do
        if [ "$STRING" == "$LINE" ]; then
            export ISLINEINFILE="yes"
        fi
    done
    if [ ! "$ISLINEINFILE" == yes ]; then
        echo "$LINE" >> "$FILE"
    fi

但是,看起来好像$ DO和$ ISLINEINFILE在完成do循环时都被清除了.如何避免这种情况?

However, it appears as if both $LINE and $ISLINEINFILE are both cleared upon finishing the do loop. How can I avoid this?

推荐答案

使用 shell

如果我们只想对您的代码进行最小的更改以使其正常运行,我们要做的就是切换输入重定向:

Using shell

If we want to make just the minimal change to your code to get it working, all we need to do is switch the input redirection:

string=foobar
while read line
do
    if [ "$string" == "$line" ]; then
        islineinfile="yes"
    fi
done <"$file"
if [ ! "$islineinfile" == yes ]; then
    echo "$string" >> "$file"
fi

在上面,我们更改了 cat"$ file" |while do ... done<"$ file" .进行了这一更改后, while 循环不再位于子shell中,因此,在循环中创建的shell变量将在循环完成后继续存在.

In the above, we changed cat "$file" | while do ...done to while do...done<"$file". With this one change, the while loop is no longer in a subshell and, consequently, shell variables created in the loop live on after the loop completes.

我相信您的整个脚本都可以替换为:

I believe that the whole of your script can be replaced with:

sed -i.bak '/^foobar$/H; ${x;s/././;x;t; s/$/\nfoobar/}' file*

上面的代码在每个文件的末尾添加了 foobar 行,而每个文件的末尾都没有与 ^ foobar $ 匹配的行.

The above adds line foobar to the end of each file that doesn't already have a line that matches ^foobar$.

上面显示 file * 作为sed的最后一个参数.这会将更改应用到与glob匹配的所有文件.如果愿意,可以单独列出特定文件.

The above shows file* as the final argument to sed. This will apply the change to all files matching the glob. You could list specific files individually if you prefer.

以上内容已在GNU sed(linux)上进行了测试.BSD/OSX sed可能需要稍作修改.

The above was tested on GNU sed (linux). Minor modifications may be needed for BSD/OSX sed.

awk -i inplace -v s="foobar" '$0==s{f=1} {print} ENDFILE{if (f==0) print s; f=0}' file*

就像sed命令一样,它可以在一个命令中处理多个文件.

Like the sed command, this can tackle multiple files all in one command.

这篇关于为什么我在do循环中设置的变量消失了?(unix壳)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆