3

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.

learningbee
  • 333
  • 1
  • 5
  • 11
  • It is NOT a directory check. `if` checks the return of the execution of `/fgallery/fgallery ...` If the command returns an `error` condition (e.g. NOT `0`), then `mkdir` is called. – David C. Rankin May 17 '17 at 19:32
  • 3
    It means if `/fgallery/fgallery` command doesn't exit with status 0 (it fails), run the `mkdir` command. – codeforester May 17 '17 at 19:33
  • 1
    Good catch, I was still stuck in C-mode. – David C. Rankin May 17 '17 at 19:36
  • Frankly, the code looks backwards. Why not simply run `mkdir` first to *ensure* the directory exists, then run `fgallery`? – chepner May 17 '17 at 19:39
  • The condition in an `if` is *always* a command (possibly preceded by `!` to negate it). A directory existence test, for example, might look like `if [ -d /foo/bar ]`. In that condition, `[` is a command, nearly equivalent to the `test` command; it's not as you might reasonably assume, a built-in part of the shell's syntax. `[` is the most common command to use as a condition, but you can use any command you like. – Keith Thompson May 18 '17 at 01:20

1 Answers1

3

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:

Community
  • 1
  • 1
codeforester
  • 39,467
  • 16
  • 112
  • 140