0

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?

4

2 に答える 2

2

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"
于 2012-09-25T05:36:14.373 に答える
0

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"
于 2012-09-25T05:40:03.400 に答える