AbreQueVoy
AbreQueVoy

Reputation: 2316

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

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?

Upvotes: 0

Views: 206

Answers (1)

KamilCuk
KamilCuk

Reputation: 141473

'[ -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") ]"

Upvotes: 4

Related Questions