waldyr.ar
waldyr.ar

Reputation: 15224

Shellscript backslashed and spaced parameter

So, what I'm trying to do is if the user didn't pass a path as argument to script, the script shall use the current directory. If a path is passed use it instead.

instdir="$(pwd)/"
if [ -n "$1" ] ; then
  instdir="$1"
fi
cd $instdir

Errors

./script.sh /path/to/a\ folder/

outputs: cd: /path/to/a: File or folder not found

./script.sh "/path/to/a\ folder/"

outputs: cd: /path/to/a\: File or folder not found

What am I doing wrong here?

Upvotes: 0

Views: 77

Answers (2)

Rody Oldenhuis
Rody Oldenhuis

Reputation: 38032

If you pass a path with spaces in it as an argument, it will cause problems. If not now, then in the future. I'd suggest you do the following (provided the path is the only argument):

instdir="$(pwd)"

if [[ -d "$@" ]]; then
  instdir="$@"  
fi

cd "$instdir"

Upvotes: 0

James Waldby - jwpat7
James Waldby - jwpat7

Reputation: 8711

Changing cd $instdir to cd "$instdir" should fix that particular problem. Without the quotes, the a and folder parts of a folder are treated as separate parameters.

Note, instead of the three-line if statement to set instdir, write:

[ "$1" ] && instdir="$1"

Upvotes: 2

Related Questions