Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

single-line if statement in a shell script not working

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?

like image 402
Alexander Bird Avatar asked Feb 24 '12 20:02

Alexander Bird


2 Answers

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 :)

like image 133
Alexander Bird Avatar answered Oct 22 '22 19:10

Alexander Bird


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
like image 33
Ярослав Рахматуллин Avatar answered Oct 22 '22 18:10

Ярослав Рахматуллин