How to skip comment line (#space) in bash for loop

With the following code:

#!/bin/bash
export LC_ALL=C

for input_file in $(<inputflist.txt)
do
    case "$input_file" in \#*) continue ;; esac
    echo $input_file

done

      

And inputflist.txt

with the following content:

# foo.txt
bar.txt

      

I expect it to just print the last line bar.txt

, but instead print this:

foo.txt
bar.txt

      

What's the correct way to do this?

+3


source to share


3 answers


This should work:

while IFS= read -r line; do
   [[ $line =~ ^[[:blank:]]*# ]] && continue
   echo "$line"
done < inputflist.txt

      



Output:

bar.txt

      

+3


source


Don't read lines from , use a while loop:

while IFS= read -r line;do
[[ $line =~ ^[[:space:]]*# ]] || echo "$line"
done <file

      



Note:

+3


source


what's wrong with

for input_file in $(grep -v "^#" inputflist.txt); do
  echo $input_file
done

      

or simply

grep -v "^#" inputflist.txt

      

?

+2


source







All Articles