How to prevent filename expansion in for loop in bash

前端 未结 2 365
盖世英雄少女心
盖世英雄少女心 2021-01-19 21:53

In a for loop like this,

for i in `cat *.input`; do
    echo \"$i\"
done

if one of the input file contains entries like *a, i

相关标签:
2条回答
  • 2021-01-19 22:08

    For the example you have, a simple cat *.input will do the same thing.

    0 讨论(0)
  • 2021-01-19 22:12

    This will cat the contents of all the files and iterate over the lines of the result:

    while read -r i
    do
        echo "$i"
    done < <(cat *.input)
    

    If the files contain globbing characters, they won't be expanded. They keys are to not use for and to quote your variable.

    In Bourne-derived shells that do not support process substitution, this is equivalent:

    cat *.input | while read -r i
    do
        echo "$i"
    done
    

    The reason not to do that in Bash is that it creates a subshell and when the subshell (loop) exits, the values of variables set within and any cd directory changes will be lost.

    0 讨论(0)
提交回复
热议问题