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?
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 :)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With