Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Bash if statement that invokes a command

Does anyone know what this is doing:

if ! /fgallery/fgallery -v -j3 /images /usr/share/nginx/html/ "${GALLERY_TITLE:-Gallery}"; then
  mkdir -p /usr/share/nginx/html

I understand the first part is saying if /fgallery/fgallery directory doesn't exist but after this it it not clear for me.

like image 911
Donislav Belev Avatar asked Jun 08 '26 19:06

Donislav Belev


1 Answers

In Bash, we can build an if based on the exit status of a command this way:

if command; then
  echo "Command succeeded"
else
  echo "Command failed"
fi

then part is executed when the command exits with 0 and else part otherwise.

Your code is doing exactly that.

It can be rewritten as:

/fgallery/fgallery -v -j3 /images /usr/share/nginx/html/ "${GALLERY_TITLE:-Gallery}"; fgallery_status=$?
if [ "$fgallery_status" -ne 0 ]; then
  mkdir -p /usr/share/nginx/html
fi

But the former construct is more elegant and less error prone.


See these posts:

  • How to conditionally do something if a command succeeded or failed
  • Why is testing "$?" to see if a command succeeded or not, an antipattern?
like image 131
codeforester Avatar answered Jun 10 '26 10:06

codeforester



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!