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
;;
----
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.