Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
    
What are you actually trying to do? readlink -f $0 seems like a broken way to get $SHELL –  Michael Mrozek Jan 31 '12 at 4:08
    
@MichaelMrozek In a script, $0 is the path to the script. I don't see how it would be useful outside a script. –  Gilles Jan 31 '12 at 23:53
    
@Gilles Oh, I assumed this was happening in a shell. That's less broken then –  Michael Mrozek Feb 1 '12 at 0:23
add comment

2 Answers

up vote 6 down vote accepted

This should do the same error 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 the -b error where come from.

Try instead

echo $(dirname `readlink -f -- $0`)
share|improve this answer
add comment

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.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.