0

I need to get the path of script.

I can do this manually with pwd but after searching online and I found this script:

DIR=$( cd $(dirname $0) ; pwd)

I don't know what it means. Can someone please explain?

edit:this script is different from that script

0

2 Answers 2

2

It identifies the directory that contains the script (which might be different than the current working directory).

You'd commonly use a pattern like this if you needed to refer to files in the same directory:

# contents of myscript.sh
DIR=$( cd $(dirname $0) ; pwd)
cat $DIR/some-file-next-to-my-script.txt

Then from anywhere on the file system:

/path/to/myscript.sh

would actually print the contents of some-file-next-to-my-script.txt. If you stuck to pwd alone, you'd be looking for that file in your current working directory, which may or may not be the behavior you want.

Breaking down the command:

$( cd $(dirname $0); pwd)
        ^^^^^^^^^^

That identifies the directory containing $0. If you invoked the script as /path/to/myscript.txt, then dirname $0 evaluates to /path/to. If you invoked it as ./myscript.txt, then dirname $0 simply evaluates to ..

$( cd $(dirname $0); pwd)
^^^^^^^^^^^^^^^^^^^^    ^

Change to the directory as before, but critically, in a subshell so that your working directory isn't modified.

Then the final pwd simply prints out that current working directory, which will always be expanded to the full path. That value is then stored in the DIR variable in your example.

Sign up to request clarification or add additional context in comments.

7 Comments

what is the use use of $0 after dirname
$0 is the name of the script. In this example, it would be /path/to/myscript.sh (if that's how you called it). Or if you did cd /path/to and called it as ./myscript.sh, then $0 would be ./myscript,sh. Because $0 changes its value depending on how exactly the script is called, people do exactly the trick you asked about to try to find where the script is being run from.
thanks for your answer. so does this tell me where my script file is located in './myscript.sh'
Added a bit more to the explanation to make it clearer what is going on.
I think this answer is perfect Thank you
|
1

DIR=$( cd $(dirname $0) ; pwd )

suppose your script is /home/lanzhiwang/work/py_web/multimediaapi_lab/pukep.py

$0 is pukep.py

$(dirname $0) is /home/lanzhiwang/work/py_web/multimediaapi_lab/

cd /home/lanzhiwang/work/py_web/multimediaapi_lab/

pwd

DIR = /home/lanzhiwang/work/py_web/multimediaapi_lab/

1 Comment

$0 is pukep.py can you please elaborate this point?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.