I am writing a bash script.
Step 1 - Fetch some meta data via curl
and write to a file.
Step 2 - Check if the file is empty. If the file is empty, log out "File is empty. Exiting..." and exit with status code 1. If the file is not empty, continue to Step 3.
Step 3 - Further process the file.
So Im trying to optimize Step 2 into one line.
This is what I have tried so far.
[ -s sp_metadata.xml ] || echo "ERROR - SP Metadata returned null. Exiting..." && exit 1
Now if the file is empty, I get the following result.
touch sp_metadata.xml
sh -x ./register.sh
+ [ -s sp_metadata.xml ]
+ echo ERROR - SP Metadata returned null. Exiting...
ERROR - SP Metadata returned null. Exiting...
+ exit 1
But when I write data to the file, I get
echo "Test" > sp_metadata.xml
sh -x ./register.sh
+ [ -s sp_metadata.xml ]
+ exit 1
Looks like it is running exit 1
every time. I guess this is because of the &&
.
I tried
[ -s sp_metadata.xml ] || echo "ERROR - SP Metadata returned null. Exiting..." ; exit 1
and also tried
[ -s sp_metadata.xml ] || (echo "ERROR - SP Metadata returned null. Exiting..." && exit 1)
But it did not work. Any ideas what is wrong with my syntax ?
[ -s sp_metadata.xml ] || (echo "ERROR - SP Metadata returned null. Exiting..."; \
exit 1)
doesn't work because you are creating a subshell, so exit 1
basically terminates the subshell, but not the parent script.
So you should try instead:
[ -s sp_metadata.xml ] || { echo "ERROR - SP Metadata returned null. Exiting..."; \
exit 1; }
which should work (and also avoids the cost of creating a subshell).
It should be noted that the ;
before the closing brace is mandatory.