However bash I acquire the way of the listing successful which a Bash book is situated, wrong that book?
I privation to usage a Bash book arsenic a launcher for different exertion. I privation to alteration the running listing to the 1 wherever the Bash book is situated, truthful I tin run connected the records-data successful that listing, similar truthful:
$ ./application
#!/usr/bin/env bashSCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
is a utile 1-liner which volition springiness you the afloat listing sanction of the book nary substance wherever it is being referred to as from.
It volition activity arsenic agelong arsenic the past constituent of the way utilized to discovery the book is not a symlink (listing hyperlinks are Fine). If you besides privation to resoluteness immoderate hyperlinks to the book itself, you demand a multi-formation resolution:
#!/usr/bin/env bashget_script_dir(){ local SOURCE_PATH="${BASH_SOURCE[0]}" local SYMLINK_DIR local SCRIPT_DIR # Resolve symlinks recursively while [ -L "$SOURCE_PATH" ]; do # Get symlink directory SYMLINK_DIR="$( cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd )" # Resolve symlink target (relative or absolute) SOURCE_PATH="$(readlink "$SOURCE_PATH")" # Check if candidate path is relative or absolute if [[ $SOURCE_PATH != /* ]]; then # Candidate path is relative, resolve to full path SOURCE_PATH=$SYMLINK_DIR/$SOURCE_PATH fi done # Get final script directory path from fully resolved source path SCRIPT_DIR="$(cd -P "$( dirname "$SOURCE_PATH" )" >/dev/null 2>&1 && pwd)" echo "$SCRIPT_DIR"}echo "get_script_dir: $(get_script_dir)"
This past 1 volition activity with immoderate operation of aliases, source
, bash -c
, symlinks, and so on.
Beware: if you cd
to a antithetic listing earlier moving this snippet, the consequence whitethorn beryllium incorrect!
Besides, ticker retired for $CDPATH
gotchas, and stderr output broadside results if the person has well overridden cd to redirect output to stderr alternatively (together with flight sequences, specified arsenic once calling update_terminal_cwd >&2
connected Mac). Including >/dev/null 2>&1
astatine the extremity of your cd
bid volition return attention of some potentialities.
To realize however it plant, attempt moving this much verbose signifier:
#!/usr/bin/env bashSOURCE=${BASH_SOURCE[0]}while [ -L "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink TARGET=$(readlink "$SOURCE") if [[ $TARGET == /* ]]; then echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'" SOURCE=$TARGET else DIR=$( dirname "$SOURCE" ) echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')" SOURCE=$DIR/$TARGET # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located fidoneecho "SOURCE is '$SOURCE'"RDIR=$( dirname "$SOURCE" )DIR=$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )if [ "$DIR" != "$RDIR" ]; then echo "DIR '$RDIR' resolves to '$DIR'"fiecho "DIR is '$DIR'"
And it volition mark thing similar:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')SOURCE is './sym2/scriptdir.sh'DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
Usage dirname "$0"
:
trial.sh:
#!/usr/bin/env bashecho "The script you are running has:"echo "basename: [$(basename "$0")]"echo "dirname : [$(dirname "$0")]"echo "pwd : [$(pwd)]"
Utilizing pwd
unsocial volition not activity if you are not moving the book from the listing it is contained successful.
[~]$ pwd/home/matt[~]$ ./test.shThe script you are running has:basename: [test.sh]dirname : [/home/matt]pwd : [/home/matt][~]$ cd /tmp[~/tmp]$ ~/test.shThe script you are running has:basename: [test.sh]dirname : [/home/matt]pwd : [/tmp]
Navigating record programs from the bid formation is a cardinal accomplishment for anybody running with Bash. 1 communal project is figuring out the listing wherever a circumstantial record, specified arsenic a Bash publication, is positioned, particularly once you're running inside that record itself. This seemingly elemental motion opens ahead a assortment of approaches utilizing Bash instructions and methods. Knowing however to execute this not lone enhances your scripting capabilities however besides improves your general ratio once managing information and directories. Successful this station, we volition research antithetic strategies to programmatically detect the listing of a Bash publication, straight from inside the publication, guaranteeing you tin confidently grip specified duties successful your scripts and bid-formation workflows.
However to Discovery the Listing of a Bash Publication From Inside?
Uncovering the listing of a Bash publication from inside the publication itself includes leveraging Bash's constructed-successful variables and instructions. The capital situation is that once a book is executed, it wants to programmatically find its ain determination. Respective approaches tin beryllium employed, all with its ain nuances and benefits. These strategies scope from utilizing situation variables that Bash routinely units, to using instructions similar dirname and readlink to resoluteness symbolic hyperlinks and extract listing paths. By mastering these methods, you tin make much sturdy and moveable scripts that accommodate to antithetic environments with out requiring hardcoded paths. This capableness is particularly utile successful bigger tasks wherever scripts are distributed crossed aggregate directories and demand to mention all another dynamically.
Using dirname
and readlink
to Find the Listing
The dirname and readlink instructions are almighty instruments successful Bash for manipulating record paths and resolving symbolic hyperlinks. The dirname bid extracts the listing constituent from a fixed way, piece readlink resolves symbolic hyperlinks to their existent mark. Once mixed, they tin reliably find the listing of a Bash book, equal if the book is executed by way of a symbolic nexus. This is peculiarly utile successful situations wherever scripts are positioned successful a communal "bin" listing and linked from assorted another areas. The readlink bid ensures that the resolved way factors to the existent determination of the book, careless of however it was invoked. Knowing however to usage these instructions successful tandem supplies a sturdy resolution for figuring out book areas successful analyzable record scheme constructions.
!/bin/bash SCRIPT_PATH="$(readlink -f "$0")" SCRIPT_DIR="$(dirname "$SCRIPT_PATH")" echo "The directory of this script is: $SCRIPT_DIR"
See the supra book. Archetypal, readlink -f "$0"
resolves the afloat way of the book ($0
refers to the book's sanction). Past, dirname
extracts the listing portion from that afloat way. This technique is sturdy equal if the book is a symbolic nexus.
Alternate Strategies to Get the Itemizing
Piece dirname and readlink message a dependable resolution, alternate strategies tin besides beryllium employed to get the listing itemizing of a Bash publication from inside. These approaches frequently affect utilizing situation variables that Bash routinely units once a book is executed. For case, the BASH_SOURCE adaptable tin beryllium utilized to find the way of the book being executed. Moreover, originative mixtures of instructions similar pwd (immediate running listing) and cd (alteration listing) tin beryllium utilized to navigate the record scheme and find the book's determination comparative to the actual running listing. These alternate strategies tin beryllium utile successful circumstantial situations oregon once dealing with older variations of Bash that whitethorn not full activity each options of readlink. Knowing these choices broadens your toolkit and permits you to take the about due technique primarily based connected the discourse of your scripting situation.
Present's an illustration utilizing the BASH_SOURCE
adaptable:
!/bin/bash SCRIPT_PATH="${BASH_SOURCE[0]}" SCRIPT_DIR="$(dirname "$SCRIPT_PATH")" echo "The directory of this script is: $SCRIPT_DIR"
Successful this lawsuit, BASH_SOURCE[0]
supplies the way to the book. The dirname
bid past extracts the listing. This is frequently less complicated however mightiness behave otherwise successful sourced scripts.
Beneath is a array evaluating the 2 strategies:
Technique | Bid(s) Utilized | Professionals | Cons |
---|---|---|---|
Utilizing dirname and readlink | readlink -f "$0" , dirname | Dependable, handles symbolic hyperlinks appropriately | Somewhat much analyzable |
Utilizing BASH_SOURCE | BASH_SOURCE[0] , dirname | Less complicated syntax | Whitethorn behave unexpectedly successful sourced scripts |
Realizing however to dynamically find the determination of a Bash publication from inside the publication itself is important for penning moveable and adaptable scripts. The methods mentioned, together with the usage of dirname, readlink, and BASH_SOURCE, supply sturdy options for assorted situations. Whether or not you're managing analyzable record programs oregon merely demand to guarantee your scripts tin find their dependencies, mastering these strategies volition importantly heighten your scripting capabilities. For additional speechmaking and precocious methods, see exploring sources similar the GNU Bash Guide. Moreover, knowing much astir record scheme navigation tin beryllium enhanced by studying astir Linux instructions done sources specified arsenic Reddish Chapeau's usher to Linux record direction. To deepen your knowing of Bash scripting, see exploring web sites that message elaborate tutorials and guides connected Bash scripting, specified arsenic Ammunition Scripting Tutorial. By combining these sources with applicable experimentation, you tin go proficient successful Bash scripting and record scheme manipulation. Commencement implementing these methods successful your scripts present to brand them much sturdy and moveable!
The girl farted into the jar. Fire explosion from fart
The girl farted into the jar. Fire explosion from fart from Youtube.com