0

I am trying to do something similar to "try.. catch" with bash, for which I read from this post that a good option to somehow replicate try/catch is to use the || and && operators. In my case, I have a piece of code supposed to zip some files, but the zip is actually empty, so it throw an error:

zip -v OUTPUT.zip file1 file2 >> $LOGFILE 2>&1

Then in the LOGFILE, I see:

zip error: Nothing to do! (OUTPUT.zip)
zip warning: OUTPUT.zip not found or empty
...(continued error message)

So I do this instead, to "catch the error"

{ zip -v OUTPUT.zip file1 file2 >> $LOGFILE 2>&1 } || { printf "Error while zipping!" >> $LOGFILE && exit 1 }

..which partially works. It does exit the code, but doesn't do the printf command (or at least I can't see it in the LOGFILE).

Also, although it encounters the "exit 1" command (on line 115), I also have the message (line 120 is my last line):

line 120: syntax error: unexpected end of file

What is wrong in my command? Why doesn't it do the print, and why the "unexpected end of file" message? Sorry if this question is more related to general bash programming than to the use of || &&, but I didn't know how to categorize this otherwise.

Thanks a lot!

Community
  • 1
  • 1
Arnaud
  • 417
  • 3
  • 15
  • 1
    you need a `;` semicolon before the closing `}` – Jetchisel Mar 31 '20 at 08:29
  • I recommend using `if`, `else` instead of `||` and `&&` if you don't know what happens. It's essentially the same but often more readable. Related: https://unix.stackexchange.com/q/335832/ – pasbi Mar 31 '20 at 08:33

1 Answers1

1

Within braces, you must terminate all commands with a semi-colon, as per the following transcript (you can see on the last line bash is waiting for more command to be typed in):

pax> { false; } || echo x;
x
pax> { false } || echo x;
+++> _

You also don't need to "brace up" a simple command, so the correct thing in your case would be:

zip -v OUTPUT.zip file1 file2 >> $LOGFILE 2>&1 || { echo "Error while zipping!" >> $LOGFILE ; exit 1 }

I've also used echo rather than printf, on the assumption you'll want a newline character at the end of the file, and made the exit unconditional on the success or otherwise of printf/echo.

paxdiablo
  • 772,407
  • 210
  • 1,477
  • 1,841