![]() ![]() Now you know how to use $0 and $BASH_SOURCE.Īlso how to run a command if the execution of the previous command is successful using &. I thought getting the directory of a Bash script would be super simple!Īs we have seen in this article it’s not the case… 19.8k 17 17 gold badges 99 99 silver badges 185 185 bronze badges. How can I fix this issue to avoid problems in the future python bash macos path pip Share. Then you can use the echo command to print the value of $SCRIPT_DIR. Consider adding this directory to PATH or, if you prefer to suppress this warning, use -no-warn-script-location. With $BASH_SOURCE our script becomes: #!/bin/bash As we have seen before this is true for $0 only when the script is not sourced (using the source command). The only thing that matters right now is that $BASH_SOURCE always contains the name and path of the script executed. I don’t want to get into too many details about $BASH_SOURCE that can be quite confusing at this stage. The $BASH_SOURCE array represents an alternative to $0 that is a lot more robust. This doesn’t work in the way we want, we need to find an alternative. This time we don’t get the path of the script back but just -bash. Let’s also test how $0 behaves with the source command, very common in Bash scripting to execute the lines in a script: scripts]$ source get_script_dir.sh Obviously, this approach doesn’t work well, we want a command that gives back the full path of the script when it’s executed from any directory (script directory, relative path, and absolute path). So the dirname allows, in scenario 3), to get the directory of the script. ![]() get_script_dir.shĢ) Relative path from parent directory: scripts]$ cd opt]$ scripts/get_script_dir.shģ) Absolute opt]$ /opt/scripts/get_script_dir.sh We update our script to add dirname $0: #!/bin/bashĪnd here is the output of the script in the three scenarios shown before: 1) From script directory: scripts]$. ![]() So this is not enough because only in the scenario 3) we get the full path for the script.įirst of all, to find a solution we need to introduce the dirname command that strips the last component from a file name. test.shĢ) Relative path from parent directory: opt]$ scripts/get_script_dir.shģ) Absolute ~]$ /opt/scripts/get_script_dir.sh We get the following: 1) From script directory: ~]$. Using the relative path from the parent directory /opt.From the script directory (/opt/scripts/).The first thing to look at to solve this problem is the $0 variable, used in Bash to store the first element of the command executed.Ĭreate a script called get_script_dir.sh in the directory /opt/scripts/: #!/bin/bash It’s a common thing people ask and it can be done in different ways. Have you ever tried to get the directory of your Bash script programmatically? ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |