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?

1
  • 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 Commented Sep 10, 2012 at 15:09

2 Answers 2

1

There's dirname but it requires a fork:

scriptPos=$(dirname "$0") 
Sign up to request clarification or add additional context in comments.

2 Comments

... and isn't necessarily more intuitive.
@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.
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") )

1 Comment

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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.