NateDawg87
NateDawg87

Reputation: 43

bash- reading file from stdin and arguments

So I have googled this and thought I found the answers, but it still doesnt work for me.

The program computes the average and median of rows and columns in a file of numbers...

Using the file name works:

./stats -columns test_file

Using cat does not work

cat test_file | ./stats -columns

I am not sure why it doesnt work

#file name was given 
if [[ $# -eq 2 ]]
  then
      fileName=$2
  #file name was not given
  elif [[ $# -eq 1 ]]
  then
      #file name comes from the user
      fileName=/dev/stdin
  #incorrect number of arguments
  else
      echo "Usage: stats {-rows|-cols} [file]" 1>&2
      exit 1
  fi

Upvotes: 0

Views: 248

Answers (1)

user4832408
user4832408

Reputation:

A very simple program that accepts piped input:

#!/bin/sh

stdin(){
    while IFS= read -r i
    do   printf "%s" "$i"
    done

}

stdin

Test is as follows:

echo "This is piped output" | stdin

To put that into a script / utility similar to the one in the question you might do this:

#!/bin/sh

stdin(){
    while IFS= read -r i
    do   printf "%s" "$i"
    done

}
rowbool=0
colbool=0
for i in $@
do case "$i" in
    -rows) echo "rows set"
           rowbool=1
           shift
    ;;
    -cols) echo "cols set"
           colbool=1
           shift
    ;;
   esac

done

if [[ $# -gt 0 ]]
then
     fileName=$1
fi
if [[ $# -eq 0 ]]
then fileName=$(stdin)
fi

echo "$fileName"

Upvotes: 1

Related Questions