1

I am new to bash and I have a program that sorts a csv file then prints it or saves it based on input. But it keeps on hanging on it after the if statement for the saving.

if [ "$1" = "-f" ]; then
    sort -r -t, -k5 $1>sorted.csv
elif [ "$2" = "" ]; then
    sort -r -t, -k5 $1
fi

should it not be sorting the file $1 and saving it to sorted.csv? The elif work?

1
  • echo statements are you best friend Commented Sep 5, 2013 at 22:07

2 Answers 2

5

sort is waiting for data. Did you redirect the CSV file into the script? Or did you in fact mean to pass "$2" to test?

Sign up to request clarification or add additional context in comments.

2 Comments

... Or sort "$2" instead of $1 (which should also properly be in double quotes)?
The lack of a space between $1 and > is causing $1 to be treated as a file descriptor for redirection, not as an argument to sort. It's waiting on standard input as a result.
3

The first if test looks at parameter $1 and does something when that parameter is '-f'. That something is using the same parameter in the 'sort' call which evaluate to:

sort -r -t, -k5 -f > sorted.csv

This will hang as you would have to pipe into the script the file content you wanted sorted and saved in sorted.csv. I suppose when it hangs you could always just type in the csv file contents and finish with CTRL-D :-). The'-f' would do a fold-case sort on my machine.

If what you meant was to pass in a file name:

if [ $# -gt 1 ]
then
   if [ $1 = "-f" ]
   then
      # assume $2 not a control switch for sort but a file name
      sort -r -t, -k5 $2 > sorted.csv
   fi
fi
if [ $# -eq 1 ]
then
   # assume $1 not a control switch for sort but a file name
   sort -r -t, -k5 $1
fi

1 Comment

Variable interpolations as file names should basically always be double quoted. You want "$1" pro $1 throughout, and ditto "$2".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.