开发者

When sending the result of this bash command to a file, I get an infinite loop

开发者 https://www.devze.com 2023-03-18 22:44 出处:网络
I have a directory of file, and I want to print out their result and have it saved to a file. If I do the following, I can dump to STDOUT:

I have a directory of file, and I want to print out their result and have it saved to a file. If I do the following, I can dump to STDOUT:

echo "[";
for i in ./*; do
    [[ -f $i ]] && cat $i; 
    echo ",";
done;
echo "]"

But if I do:

echo "[" < myfile.txt;
for i in ./*; do 
    [[ -f $i ]] && cat $i << myfile.txt;
    echo "," << myfile.txt;
 done;
 echo "]" 开发者_StackOverflow<< myfile.txt

I get stuck in an infinite loop. Any ideas?


The problem is that you're creating a file in ., then reading and writing to it simultaneously. You need to store myfile.txt in a different directory than the one you're processing.

Also, I suggest this approach as a shorter form of what you're doing:

{ echo "[";
for i in ./*; do
    [[ -f $i ]] && cat $i;
    echo ",";
done;
echo "]"
} > ../myfile.txt


Assuming you're using >>, then at some point $i will equal myfile.txt, and you'll try and append it to itself...

0

精彩评论

暂无评论...
验证码 换一张
取 消