(For simplicity I'll assume the file to read is the first argument - $1.)
I can do what I want externally with:
tempfile=$(mktemp)
awk '/^#/ {next}; NF == 0 {next}; {print}' "$1" > $tempfile
while read var1 var2 var3 var4 < $tempfile; do
# stuff with var1, etc.
done
However, it seems absurd to need to call awk every time I parse the config file. Is there a way to make read ignore commented or whitespace-only lines in a file, without external binaries/potential performance issues?
Answers so far are quite helpful! To clarify, I don't want to use a temp file, but I do want to read the config from a file, not from standard in. I'm well aware that I can use an input redirection when I call the script, but for various reasons that won't work in my circumstance.
I want to softcode the input to read from, e.g.:
configfile="/opt/myconfigfile.txt"
[ $# -gt 0 ] && [ -r "$1" ] && configfile="$1"
while read var1 var2 var3 var4 < "$configfile" ; do
...
But when I try this, it just reads the first line of configfile over and over until I kill the process.
Maybe this should be its own question...but it's probably a single line change from what I'm doing. Where's my error?
whilecommand list instead of redirecting into the body of the loop (see my answer below). I think your default myconfigfile.txt code will work, see my answer for a more concise (and maybe less obvious) solution to overriding the default via a reference to$1, however my answer does not check the file for readability.$1is unreadable. The script would behave as if$1was processed, while actually using the default. Depending on the context, you might want to use the$1value and let the shell print the error when the file cannot be opened for the redirection.