2

I'd like to make a shell script that can compile and run (if it compiles) a C program I created. However, if it doesn't compile I don't want it to run the executable. So far I've created this as my solution;

gcc -o assignment1 assignment1.c if [[ ?$ -eq 0 ]]; then ./assignment1; fi exit 0;

however, it keeps saying line 2 syntax error: unexpected end of file. I'm new to bash can someone explain why this isn't working

fixed syntax errors and closed if statement. Thanks to commenters.

  • 6
    You have several syntax errors; check your code with https://shellcheck.net. – chepner Jan 17 '20 at 00:44
  • 6
    You should learn to use makefiles rather than writing a custom script. – Barmar Jan 17 '20 at 00:44
  • 2
    +1 for using Makefiles - they are specifically built for this purpose. Here's a quick intro: https://www.gnu.org/software/make/manual/html_node/Introduction.html – Sharad Jan 17 '20 at 05:11
  • `if gcc -o assignment1 assignment1.c; then ./assignment1; fi` -- there's no reason to use `$?` or `[[` at all. – Charles Duffy Jan 17 '20 at 18:40

1 Answers1

1

It looks to me like you need to close your if, as well as add spaces after the brackets:

gcc -o assignment1 assignment1.c
if [[ ?$ -eq 0 ]]; then 
./assignment1; 
fi 
exit 0;

However, since this is fairly straightforward, why not use conditional execution:

gcc -o assignment1 assingment.c && ./assignment1

That way, if the first sub-command fails, the second one simply won't be run - imo that looks a lot cleaner too!

ZachChilders
  • 415
  • 3
  • 15
  • 1
    `if [[?$ -eq 0]]` is invalid. There is no need for `(` . Just `gcc -o assignment1 assignemt.c && ./assignement1` – KamilCuk Jan 17 '20 at 01:38
  • 1
    The `[?$ -eq 0]` is as invalid as `if [[?$ -eq 0]]` was. Shell is space aware, with `[[$?` it will try execute a command named ex. `[[0` and fail with no such command. – KamilCuk Jan 17 '20 at 18:35
  • My mistake - I have edited in the spaces. – ZachChilders Jan 17 '20 at 18:59