无论空格如何,完全读取每一行

Sof*_*mur 1 bash shell makefile

我的一部分makefile如下:

list:          all
               for f in \
               `less fetch/list.txt`; \
               do \
                    echo $$f; \
                    ...
               done
Run Code Online (Sandbox Code Playgroud)

fetch/list.txt 包含文件列表:

path/file1.ml
path/file2.ml
path/file 3.ml
path/file 4.ml
Run Code Online (Sandbox Code Playgroud)

问题是,即使文件名中允许空格,也会make list显示:

path/file1.ml
path/file2.ml
path/file
3.ml
path/file
4.ml
Run Code Online (Sandbox Code Playgroud)

有没有人知道让每一行都完整阅读,无论空格如何?

Eri*_*ski 5

这是一种方法:

list:
        while IFS= read -r n ; do echo "line: $$n" ; done < list.txt
Run Code Online (Sandbox Code Playgroud)

这是在行动:

$ cat list.txt 
abc
def
123 456

$ gmake
while read n ; do echo "line: $n" ; done < list.txt
line: abc
line: def
line: 123 456
line: 
Run Code Online (Sandbox Code Playgroud)

  • 这是一个bash gotcha.如果行中有反斜杠,你肯定想要`read -r`,而且你需要知道read总是去掉前导和尾随的IFS字符.所以你实际需要:`IFS = read -r ...`.或者你可以使用`mapfile/readarray -t` (2认同)