Not Yet Another Another Guide About Bash
Despite the growing adoption of tools and orchestrators like Kubernetes, Flux, and Dagger, shell commands and Bash scripts remain an integral part of a software engineer’s daily workflow.
“The total amount of Bash in the universe remains constant” — collective wisdom
I would dare say that any “trick” that can improve the general speed or knowledge regarding this matter is highly valuable. Without further ado, I will share a compilation of different commands which has helped me greatly.
- Quickly change the directory to the user's home directory (specified by
$HOME
environment variable), equivalent to runningcd ~
:
# cd without any arguments takes you to your home directory
cd
- Go Back to the Previous Directory: Going back to the previous directory (based on
$OLDPWD
internal variable) — is especially useful when navigating through long paths:
cd -
- Execute the last command: useful for rerunning the previous command
!!
- Check the return code of the last command: useful when checking various return codes (in Unix and Linux, every command returns a numeric code between 0–255):
echo $?
- Globbing “searching for files using wildcard expansion” — list files that start with the letter
a
:
# * matches any sequence of characters
ls a*
Or sometimes maybe you don’t have ls
available:
# expand and print all the files and directories in the current directory
echo .* *
- Create a nested directory structure:
mkdir -p provisioning/{datasources,notifiers,dashboards/backup}
# will create
.
└── provisioning
├── dashboards
│ └── backup
├── datasources
└── notifier
- Get the Process ID of this shell itself —
SHELL
is not always defined by the bash shell:
# echo $SHELL
ps -p $(echo $$)
- Emulating tree command — on minimal distros, tree command may not exist, therefore the following alias provides the much-needed recursive directory listing:
alias tr3='function tr3(){ find ${1:-.} | sed -e "s/[^-][^\/]*\// |/g" -e "s/|\([^ ]\)/|-\1/"; unset -f tr3;}; tr3'
- Heredoc for file creation — here document is a special-purpose code block. It uses a form of I/O redirection to feed a command list to an interactive program or a command.
Heredoc that prints the evaluated values directly to the terminal ( or even create/override a file i.e. text
by cat<<EOF>text
by redirecting the output to a file).