How would you represent EOF in bash?

前端 未结 5 1087
执念已碎
执念已碎 2020-12-24 07:31

I\'m trying to do something like

read -d EOF stdin

for word in $stdin; do stuff; done

where I want to replace \'EOF\' for an actual repre

5条回答
  •  半阙折子戏
    2020-12-24 08:10

    There isn't an end-of-file character really. When you press Ctrl-d or similar characters, the terminal driver signals to the reading application that the end of file has been reached, by returning an invalid value. The same is done by the operation system, when you have reached the end of the file. This is done by using an integer instead of a byte (so you have range similar to -2^16 .. 2^16, instead of only 0..255) and returning an out-of-range value - usually -1. But there is no character that would represent eof, because its whole purpose is to be not a character. If you want to read everything from stdin, up until the end of file, try

    stdin=$(cat)
    for word in $stdin; do stuff; done
    

    That will however read the whole standard input into the variable. You can get away with only allocating memory for one line using an array, and make read read words of a line into that array:

    while read -r -a array; do 
        for word in "${array[@]}"; do 
            stuff;
        done
    done
    

提交回复
热议问题