0

I m trying to read in data either from a file or from the user's input to process it in a bash shell script. I m very new to it and I have this code working so far when the script accepts a file as an argument. When i try to create a new file that I can read the user's inputs and process it it throws an error : $datafilepath ambiguous redirect. I feel I m very close to it but I might be missing some good syntax. Can somebody push me in a right direction? Thanks!

#!/bin/bash
if [ "$#"  = "1" ]
then
    cat >>"$datafilepath"
elif  [ "$#" = "2" ]
then
    datafilepath=$2
fi

echo Average Median
while read myLine
do
    sum=0
    med=0
    for word in $myLine
        do
            sum=`expr $sum + $word`
            echo -e $word >> medfile
        done

sort < medfile >sorted
cat sorted | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile
rm -f sorted
rm -f rowfile
done <$datafilepath 

1 Answers1

1
#!/bin/bash
if [ "$#"  = "1" ]
then
    cat >>"$datafilepath"
elif  [ "$#" = "2" ]
then
    datafilepath=$2
fi

$datafilepath first appears in line #4, but it hasn't been initialized, so it's blank. The shell '>>' won't append unless there is a filename. There needs to be a line before that that sets $datafilepath to a default filename.

Line #2: the '1' should be a '0'. Line #5: the '2' should be a '1' Line #7: the '$2' should be a '$1'

This block has a needless file "sorted":

sort < medfile >sorted
cat sorted | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile
rm -f sorted
rm -f rowfile

Suggested reduction:

sort medfile | tr '\n' '\t' > rowfile
printf "%.0f\t%.0f\n" $(echo "scale=2; $sum/5" | bc ) $(cut -d' ' -f3 rowfile)
rm -f medfile rowfile
agc
  • 7,973
  • 2
  • 29
  • 50