Read a file or read user standard input

I am having a problem while writing a bash script. I had to write a script that can be called in two ways, read a file or read standard input. However, when I used what I read, I can no longer read its standard input. Here is my code:

#!/bin/bash
FILE=$1
while read LINE; 
do
    echo "$LINE" | tr " " "\n" | tr "\t" "\n"
done < $FILE

      

+3


source to share


2 answers


The problem comes from the fact that you always give $ FILE as input for your reading. You can try to redirect the file to channel 0 if you have an argument and leave it otherwise.

#!/bin/bash
FILE=$1
if [ ! -z "$FILE" ]
then
  exec 0< "$FILE"
fi
while read LINE
do
    echo "$LINE" | tr " " "\n" | tr "\t" "\n"
done

      



exec 0< "$FILE"

tells the shell to use $ FILE as input for channel 0. Reminder: By default, it read

listens on channel 0.

0<

is the key here where it 0

indicates channel 0 and <

indicates that this is an input. When there are no arguments, exec 0< "$FILE"

will not be called, in which case channel 0 will use stdin.

+3


source


UNIX tools use a special filename by default to -

indicate that input comes from stdin. You can adapt this:

file="${1}"
if [ "${file}" = "-" ] ; then
    file=/dev/stdin # special device for stdin
fi

while read -r line ; do
    do something
done < "${file}"

      



Now you can call this tool

tool -             # reads from terminal
cmd | tool -       # used in a pipe
tool /path/to/file # reads from file

      

+2


source







All Articles