Getting the source directory of a Bash script from within

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29 http://en.wikipedia.org/wiki/Bash_%28Unix_shell%29

For instance, let s say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:

$ ./application

Answers

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.

It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"

This last one will work with any combination of aliases, source, bash -c, symlinks, etc.

http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/ http://bosker.wordpress.com/2012/02/12/bash-scripters-beware-of-the-cdpath/

To understand how it works, try running this more verbose form:

#!/bin/bash

SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
  TARGET="$(readlink "$SOURCE")"
  if [[ $TARGET == /* ]]; then
    echo "SOURCE  $SOURCE  is an absolute symlink to  $TARGET "
    SOURCE="$TARGET"
  else
    DIR="$( dirname "$SOURCE" )"
    echo "SOURCE  $SOURCE  is a relative symlink to  $TARGET  (relative to  $DIR )"
    SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
  fi
done
echo "SOURCE is  $SOURCE "
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
  echo "DIR  $RDIR  resolves to  $DIR "
fi
echo "DIR is  $DIR "

And it will print something like:

SOURCE  ./scriptdir.sh  is a relative symlink to  sym2/scriptdir.sh  (relative to  . )
SOURCE is  ./sym2/scriptdir.sh 
DIR  ./sym2  resolves to  /home/ubuntu/dotfiles/fo fo/real/real1/real2 
DIR is  /home/ubuntu/dotfiles/fo fo/real/real1/real2 

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/59895/getting-the-source-directory-of-a-bash-script-from-within

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils