Escaping space in shell script path

scriptterminal

I have tried both methods of escaping the space in the Path in the following script:

#!/bin/bash -x
PGHOME="/Applications/pgAdmin 4.app/Contents/SharedSupport"
$PGHOME/psql --username postgres -c "drop database $1"

I've also tried changing line 2 to:

PGHOME=/Applications/pgAdmin\ 4.app/Contents/SharedSupport

In both cases I get the script error:

./pg10-restoreDb.sh: line 3: /Applications/pgAdmin: No such file or directory

From the shell, I can execute /Applications/pgAdmin\ 4.app/Contents/SharedSupport/psql no problem

What could be causing this error?

Best Answer

You can either quote or escape the space when you define the variable, but then you must also double-quote it when you use it:

#!/bin/bash -x
PGHOME="/Applications/pgAdmin 4.app/Contents/SharedSupport"
"$PGHOME/psql" --username postgres -c "drop database $1"
^            ^
|            |