#!/bin/bash
cmd=$(basename $0)
curdir=$(dirname $0)
curdir=$(cd ${curdir}; pwd)
#!/bin/bash
2. Determine the script name. The $0 variable is the execution path of the script being run. For example, the execution path could have been to run the script in the current directory with ./myscript.sh. Or, it could have been called from a directory above with ../myscript.sh. Or, perhaps it might have been called using the full path of /opt/ods/poc/myscript.sh. The basename command trims off the path to leave just the script name. We assign the output of the basename command to the cmd variable so that it can be used as a common reference (${cmd}) throughout the rest of the script.
cmd=$(basename $0)
3. Determine the base directory based of the script's location. The dirname command trims off the script name leaving just the path to the script. We temporarily assign the result of the dirname output to the curdir in the first step to determining the current directory.
curdir=$(dirname $0)
4. Lastly, we change directory to the current value of ${curdir} and then use the present working directory (pwd) command to determine the fully qualified path of the directory that we are in.
curdir=$(cd ${curdir}; pwd)
You may be wondering why we didn't just stop at step 3 because technically, that is correctly the current directory. The reason is because the execution of the script can be called from a variety of ways that are not the full path name. For example, if I ran the script with ../../../myscript.sh, the first value of curdir would be "../../../", which is not the fully qualified path. However, after step 4, the fully qualified path is righly determined to be /opt/ods/poc.
I hope you find this helpful!
Blessings!
Brad
No comments:
Post a Comment