Trying to read a file line by line, but its not working, tried many different ways including below:
$ cat test.sh
#!/bin/bash
echo 'line1
line2
line3
line4
;;' > list.txt
IFS=$'\n'
for line in "$(cat list.txt)"
do
echo "line=$line"
echo "----"
done
When I run:
$ ./test.sh
line=line1
line2
line3
line4
;;
----
答案 0 :(得分:3)
Because you have used quotes around command substitution, $()
, the shell is not performing word splitting on newline (IFS=$'\n'
) (and pathname expansion), hence the whole content of the file will be taken as a single string (the first line
has it), instead of newline separated ones to iterate over.
You need to remove the quotes:
for line in $(cat list.txt)
Although it is not recommended to iterate over lines of a file using for
-cat
combo, use while
-read
instead:
while IFS= read -r line; do ...; done <list.txt