I have script that can loop over a give file
while IFS=";" read -r a b c
do
...
done <"$file"
but I also want user to use stdin.. I know how to read stdin:
while IFS=";" read -r a b c
do
...
done <"${1:-/dev/stdin}"
I want to keep loop content unchanged, and to work on the "done" statement to feed it from a file or from stdin.
I am trying to do something like
if [[ "$usefile"=="yes" ]]; then
data="$file"
else
data="${1:-/dev/stdin}"
fi
while IFS=";" read -r a b c
do
...
done <"$data"
But of course, it does not work at data="${1:-/dev/stdin}" line... the ${} is replaced and fails
tried to use data to store either filename or stdin name.
CodePudding user response:
I finally found the solution, the done statement have to be changed into
done < "${file:-/dev/stdin}"
if file is provided, it will loop over file content, otherwise it will loop over /dev/stdin
Final script:
# note: leave file empty to loop over stdin.
while IFS=";" read -r a b c
do
...
done < "${file:-/dev/stdin}"