Shell Script and spaces in the path

I have a large script shell that handles different things.

He will get his own location as follows ...

BASEDIR=`dirname $0`/..
BASEDIR=`(cd "$BASEDIR"; pwd)`

then BASEDIR will be used to create other variables, such as

REPO="$BASEDIR"/repo

But the problem is that this shell script does not work if the path contains spaces in which it is executed.

So the question is: is there a good solution to solve this problem?

+5
source share
7 answers

Be sure to duplicate anything that may contain spaces:

BASEDIR="`dirname $0`"
BASEDIR="`(cd \"$BASEDIR\"; pwd)`"
+7
source

The answer is "Quotes Everywhere."

If the path that you are walking in takes place in it, then it dirname $0does not work.

$ cat quote-test.sh
#!/bin/sh

test_dirname_noquote () {
        printf 'no quotes: '
        dirname $1
}
test_dirname_quote () {
        printf 'quotes: '
        dirname "$1"
}

test_dirname_noquote '/path/to/file with spaces/in.it'
test_dirname_quote '/path/to/file with spaces/in.it'

$ sh quote-test.sh
no quotes: usage: dirname string
quotes: /path/to/file with spaces

Also try this fun example.

#!/bin/sh

mkdir -p /tmp/foo/bar/baz
cd /tmp/foo
ln -s bar quux
cd quux
cat >>find-me.sh<<"."
#!/bin/sh

self_dir="$(dirname $0)"
base_dir="$( (cd "$self_dir/.." ; pwd -P) )"
repo="$base_dir/repo"

printf 'self: %s\n' "$self_dir"
printf 'base: %s\n' "$base_dir"
printf 'repo: %s\n' "$repo"
.

sh find-me.sh

rm -rf /tmp/foo

Startup Result:

$ sh example.sh
self: .
base: /tmp/foo
repo: /tmp/foo/repo
+5
source

:

REPO="$BASEDIR/repo"
+2

/ .

. script? ,

, -

BASEDIR=$(readlink -f $0)

, REPO="$BASEDIR"/repo, , .

+2

. REPO? " " ?

#!/bin/sh
BASEDIR=`dirname $0`/..
BASEDIR=`(cd "$BASEDIR"; pwd)`
REPO="$BASEDIR"/repo
echo $REPO

".../a b/c d". ".../a b/repo", .

, ... " " - , .

+1

unix , , , , .

, BASEDIR , script (..),

, .

.////../

BASEDIR=`dirname $0`/..

, $REPO, , , $REPO - script, .

.

#!/bin/ksh

BASEDIR=`dirname $0`/..
$REPO="$BASEDIR"/repo

if [ ! -d ["$REPO"] 
then
  echo "$REPO does not exist!"
fi
+1

, :

 BASEDIR=`dirname "${0}"`/..
+1

All Articles