Your shell will look up the-script in $PATH. Now, there's a difference if the script command name as invoked doesn't contain a slash. Note however that if you read from $0, you'll break the script as you consume the input. Now, you may argue that /dev/fd/x is a path to that script. To avoid race conditions (in which case $0 will contain /dev/fd/x). There's an exception for setuid/setgid scripts on some systems, where the system will open the script on some fd x and run instead: exec("/bin/sh", ) (if it doesn't contain a she-bang, or more generally if the system returns a ENOEXEC error, then it's your shell that will do the same thing) If the script contains a #! /bin/sh - she-bang for instance, the system will transform that to: exec("/bin/sh", ) Your shell will do a: exec("the/script", ) $0 is assigned from the argument specifying the script as passed to the interpreter.įor example, in: the-shell -shell-options the/script its args (assuming there's a readlink command and it supports -e) generally is a good enough way to obtain the canonical absolute path to the script. In the most common cases, $0 will contain a path, absolute or relative to the script, so script_path=$(readlink -e - "$0") Are there situations where $0 would not include the directory?.Is the behavior different on other systems?.The comment (upvoted 7 times) says "that will not work if the script is in your path". The answer suggests using $(dirname $0) to get the directory of the current script. So that looks like it would be safe to pass to another command.īut then I came across a comment on Stack Overflow that confused me. In that case, the value of $0 is the absolute path. In these tests, the value of $0 is always exactly how the script was invoked, except if it is invoked without any path component. These are my results: > cd /usr/local/bin/test I created an executable file in /usr/local/bin called scriptname with one line echo $0 and invoked it from different locations. The last one actually implies to me that it wouldn't. None of these make it clear whether or not the value of $0 would include the directory if the script was invoked without it. I searched for an explanation of the special variables and found the following descriptions of $0: I was thinking of something like this: grep '^#h ' - "$0" | sed -e 's/#h //'īut then I wondered what would happen if the script was located in a directory that was in PATH and called without explicitly specifying the directory. I want to grep the current script so I can print out help and version information from the comments section at the top.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |