Showing posts with label absolute path;path of script;running script path;path of running script. Show all posts
Showing posts with label absolute path;path of script;running script path;path of running script. Show all posts

Wednesday, November 15, 2023

Obtain the #absolute #path of the #directory containing the currently executing script

MYPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"

Then you can use $MYPATH variable as you need to access files in the current directory where the currently running script is residing.

$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )

1. `$(...)`: This syntax is used for command substitution. Whatever is inside `$(...)` will be executed, and the output of that command will replace `$(...)`.

2. `cd -- "$(dirname "$0")"`: This command changes the current directory (`cd`) to the directory containing the script. Here, `"$0"` represents the name of the script, and `dirname "$0"` extracts the directory name from the script's path. The double quotes and `$(...)` ensure that spaces or special characters in the directory path are handled correctly.

3. `>/dev/null 2>&1`: This part is a redirection. `>/dev/null` redirects standard output (stdout) to `/dev/null`, which essentially discards any output from the `cd` command. `2>&1` redirects standard error (stderr) to the same place as stdout, which is `/dev/null` in this case, effectively suppressing any error messages.

4. `;`: This semicolon allows the chaining of commands in a single line. It separates the `cd` command from the subsequent `pwd` command.

5. `pwd -P`: This command (`pwd`) prints the working directory. The `-P` option stands for `--physical` and is used to get the physical current working directory without any symbolic links.

To summarize, this line of code changes the current directory to the directory containing the script, suppresses any output or errors from the `cd` command, and then prints the absolute path of that directory.


#CommandSubstitution, #AbsolutePaths, #DirectoryNavigation, #BashScripting, #CurrentDirectory, #PathManipulation, #RedirectOutput, #SuppressErrors, #PhysicalDirectories, #ScriptExecution

Featured Posts

Kali Linux Remote Desktop: Access GNOME from Windows Using Native RDP

  Kali Linux + GNOME 50 + GNOME Remote Desktop + Windows Remote Desktop (MSTSC) Getting a full GNOME desktop remotely on Kali Linux can be ...