1
unzip /test_data/sample.ZIP -d /data/Traget/
if [ "$?" = 1 ]; then
    echo " Unzipping of files failed"
    exit 1
fi

The script is archiving data and trying to write at the location mentioned but the directory /data/Traget/ does not have access to write and hence the script is failing.... But its not throwing status 1. Could someone please help

Thank You

John Zwinck
  • 239,568
  • 38
  • 324
  • 436
PPPP
  • 561
  • 1
  • 4
  • 14
  • 1
    Did you check what status it actually returned ? It's customary to return 0 on success, but different codes for failure. Perhaps your unzip command returned 2 or 3 ? – nos Nov 29 '16 at 14:07

2 Answers2

1

It's so much simpler than that:

set -e
set -o pipefail

unzip /test_data/sample.ZIP -d /data/Target/

All Bash scripts you write should start with those two options. What they do is to terminate the script with an error if any single command fails.

It's the opposite of the abominable "On Error Resume Next" from VBA, if anyone remembers that!

But if you really need to write tedious error handling code everywhere, you'd do it this way:

if ! unzip /test_data/sample.ZIP -d /data/Traget/; then
    echo " Unzipping of files failed"
    exit 1
fi
Community
  • 1
  • 1
John Zwinck
  • 239,568
  • 38
  • 324
  • 436
0

You should reverse your logic. unzip returns 0 on success, and any number of exit codes on error. So make it:

unzip /test_data/sample.ZIP -d /data/Traget/
if [ "$?" -ne 0 ]; then
    echo " Unzipping of files failed"
    exit 1
fi

You can easily check what unzip returns yourself too by running echo $? after the command you want to know the exit status from.

Here's what happens when I run a similar command:

$ unzip dd.zip  -d /tmp/a/b/
Archive:  dd.zip
error:  cannot create /tmp/a/b/filename
        Permission denied
$ echo $?
50

So unzip returns 50 when it fails in this manner.

nos
  • 223,662
  • 58
  • 417
  • 506