Home > database >  Checking if remote directory exists returns exit code 1, but the opposite option gets executed
Checking if remote directory exists returns exit code 1, but the opposite option gets executed

Time:03-17

This check gets invoked:

  - echo "Everything works fine until now."
  - >
     if ssh user@$TEST_SERVER '[ -d $BUILD_DIR ]'; then
       echo "Directory exists, continuing."
     else
       ssh user@$TEST_SERVER 'mkdir -p $BUILD_DIR'
     fi
  - scp some_script.sh user@$TEST_SERVER:$BUILD_DIR/
  - echo "I do not even get executed; previous line fails..."

In the output I can see the "Directory exists, continuing." sentence: the job continues as if the directory existed in the remote server, and then the line with scp command gets launched, failing to copy the script file to a non-existing directory.

When I make a check from my machine, launching the same command, I get an exit code 1:

$ ssh [email protected] '[ -d /var/www/build_1 ]'
$ echo $?
1

What is wrong in there?

CodePudding user response:

'[ -d $BUILD_DIR ]'

is inside single quotes, BUILD_DIR is not set on the remote so it expands to nothing, which expands to [ -d ] - -d is not an empty string, so [ exits with success.

You want:

"[ -d $BUILD_DIR ]"

or yet better:

"[ -d $(printf "%q" "$BUILD_DIR") ]"
  • Related