12

When I run the following as a normal user, everything is fine:

$(dirname `readlink -f $0`)

But after I switched to root, the following error occurred:

readlink: invalid option -- 'b'
Try `readlink --help' for more information.
dirname: missing operand
Try `dirname --help' for more information.

Any ideas? I tried on local Fedora 16 and Amazon EC2, both running bash shell.

Apologize that I did not further illustrate the issue here. Here is the scenario:

Using normal user account:

$ pwd 
/home/myuser 
$ export MY_DIR=$(dirname `readlink -f $0`) 
$ echo MY_DIR 
/home/myuser

Using root user account:

# pwd
/root
# export ROOT_DIR=$(dirname `readlink -f $0`)
readlink: invalid option -- 'b'
Try `readlink --help' for more information.
dirname: missing operand
Try `dirname --help' for more information.

export ROOT_DIR=echo $(dirname readlink -f -- $0)

echo $ROOT_DIR

/root

Jakov
  • 103
  • 4
d4v1dv00
  • 375

2 Answers2

17

This should be the same error as in a user login shell, because in a login shell the 0 shell parameter, expanding to the name of the current process, gives -bash, the minus indicating the login shell. You now see where the -b error comes from.

Try instead

echo "$( dirname "$(readlink -f -- "$0")" )"
Kusalananda
  • 333,661
enzotib
  • 51,661
4

If you really want the directory name of the shell script which is being run:

script_dir="$(dirname -- "$(readlink -f -- "$0")")"

Yes, it's a bit cludgy, but it's safe.

If you want the current shell, you can try @MichaelMrozek's suggestion of using $SHELL.

l0b0
  • 51,350