1

Possible Duplicate:
In the bash script how do I know the script file name?

I often need the file system of a bash script to reference other needed resources. Normally use the following code in line after the shebang line. It sets a variable called 'scriptPos' contains the current path of the scripts

scriptPos=${0%/*}

It works fine, but is there something more intuitive to replace the shell expansion?

Community
  • 1
  • 1
OkieOth
  • 3,604
  • 1
  • 19
  • 29
  • It contains a similar solution like my way. The problem is I forget the syntax every time and only take it with copy and paste from script to script :-D – OkieOth Sep 10 '12 at 15:09

2 Answers2

1

There's dirname but it requires a fork:

scriptPos=$(dirname "$0") 
Thor
  • 45,082
  • 11
  • 119
  • 130
  • ... and isn't necessarily more intuitive. – tripleee Sep 10 '12 at 15:23
  • @user1651840: try `strace -e execve -f` with `dirname` in a script. @tripleee: well I seem to remember this one, while I always have check the parameter expansion. – Thor Sep 10 '12 at 15:30
0

One option is

scriptPos=$(dirname $0)

which comes at the cost of an extra process, but is more self-descriptive. If the script is in the current directly, the output differs (for the better, in my opinion):

#!/bin/bash
scriptPos=$(dirname $0)

echo '$0:' $0
echo 'dirname:' $scriptPos
echo 'expansion:' ${0%/*}

$ bash tmp.bash
$0: tmp.bash
dirname: .
expansion: tmp.bash

UPDATE: An attempt to address the shortcomings pointed out by jm666.

#!/bin/bash
scriptPos=$( v=$(readlink "$0") && echo $(dirname "$v") || echo $(dirname "$0") )
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    this will not work 1) with symlinked script. (will show the dirname for the symlink). 2) for the relative path will show "../../dir", not the place of the script in the filesystem. – clt60 Sep 10 '12 at 19:38