basename and dirname Reference for CI Scripts
basename strips the directory from a path; dirname strips the filename.
These two split a path into its parts. The most common CI use is computing a script\u2019s own directory so it can reference sibling files regardless of the working directory.
Common flags/usage
- basename PATH: print the final path component
- basename PATH SUFFIX: also strip a trailing suffix like .sh
- dirname PATH: print everything except the final component
- basename -a: process multiple paths at once
- Combine with $0 to locate the running script
Example
shell
SCRIPT_DIR=$(dirname "$(readlink -f "$0")")
source "${SCRIPT_DIR}/lib/common.sh"
NAME=$(basename "${ARTIFACT}" .tar.gz)In CI
The SCRIPT_DIR=$(dirname "$(readlink -f "$0")") idiom lets a script find its siblings no matter where it is invoked from, which matters because CI working directories vary. Always quote the path arguments so spaces do not split them, and note BSD basename lacks some GNU options.
Key takeaways
- dirname plus readlink -f resolves a script\u2019s own directory reliably.
- basename PATH .ext strips both the directory and a known suffix.
- Quote path arguments so spaces in paths do not split them.
Related guides
readlink -f Command Reference for CI Scriptsreadlink -f resolves a path to its canonical absolute form in CI. Reference for -f, -e, and -m, plus the macO…
cp Command Reference for CI Scriptscp copies files and directories in CI for staging artifacts. Reference for -r, -p, -a, and trailing-slash beh…
ln -s Command Reference for CI Scriptsln -s creates symbolic links in CI for toolchains and shared paths. Reference for -s, -f, -n, and -r, plus th…
mktemp Command Reference for CI Scriptsmktemp creates unique temp files and directories safely in CI. Reference for -d, templates, and -t, plus the…