ESXi shell: appending the parent directory of a script to the path and starting a new shell, even if the script is symlinked
Posted by jpluimers on 2021/10/26
I needed a way to append the directory of a script to the path as all my tool scripts are in there, and I did not want to modify any profile scripts as these might be modified during ESXi upgrade.
First you need the full script filename through readlink
then toe parent directory name through dirname
:
-
- [Wayback] string – bash : Bad Substitution – Stack Overflow
me@pc:~$ readlink -f $(which sh) /bin/dash
By [Wayback] Vanni Totaro.
- [Wayback] shell – Getting parent’s directory name by piping the results of dirname to basename in a Bash script – Stack Overflow
# echo 'test/90_2a5/Windows' | xargs dirname | xargs basename90_2a5
- [Wayback] string – bash : Bad Substitution – Stack Overflow
Note there might be dragons with more symlinks or different shells:
- [Wayback] bash – How to get script directory in POSIX sh? – Stack Overflow
- [Wayback] shell – How can I simply retrieve the absolute path of the current script (multi OS solution)? – Stack Overflow
I created the script below. It is not perfect, but for my situation it gets the job done.
If you do not start a new shell, then the export is lost as a new dash
shell process is started for each script that runs from the terminal or console.
# cat /opt/bin/append-script-directory-to-path-and-start-new-shell.sh #!/bin/sh # Absolute path to this script, e.g. /home/user/bin/foo.sh # echo "'$0'" SCRIPT=$(readlink -f "$0") # Absolute path this script is in, thus /home/user/bin SCRIPTPATH=$(dirname "$SCRIPT") # echo Appending to $PATH: $SCRIPTPATH export PATH=$PATH:$SCRIPTPATH sh
–jeroen
Leave a Reply