Bash – Strange behavior in $(dirname `readlink -f $0`)

bash

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.

edit for illustration.

apologze 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:

# 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

Best Answer

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")" )"
Related Question