single-line if statement in a shell script not working

34,398

Solution 1

it turns out that there needs to be a space between the if and the [. Also, I put in the then and fi keywords.

The following worked.

#!/bin/bash
cat input$1 | ./prog$1 > output$1 && if [ "$2" != "" ]; then diff output$1 expected$1; fi

EDIT:

as commented below (and in another answer), this can elegantly be shortened to:

cat input$1 | ./prog$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1

in which case I don't even have to remember any of the rules about how to use the if construct :)

Solution 2

drop the if. [] will spawn a new "command" and you can run diff or whatever after if it exits with 0 using && (run next if previous exits ok). here:

echo lol &&  [ $((10-1)) -eq 9 ] && echo math\!

and your one-liner:

#!/bin/bash
cat input$1 | ./prog$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1
Share:
34,398
Alexander Bird
Author by

Alexander Bird

I'm currently working for Itential.

Updated on February 29, 2020

Comments

  • Alexander Bird
    Alexander Bird about 4 years

    This is my code:

    #!/bin/bash
    cat input$1 | ./prog$1 > output$1 && if[ "$2" != "" ]; diff output$1 expected$1;
    

    This then happens:

    $ ./run.sh
    ./run.sh: line 2: if[ no !=  ]: command not found
    $
    

    I thought that I could run if statements on one line? is that what the problem is?

  • glenn jackman
    glenn jackman about 12 years
    You can shorten that a bit: ./prog$1 < input$1 > output$1 && [ "$2" != "" ] && diff output$1 expected$1