Bash - Bourne again shell
Bash is the default shell of most Linux distros.
Navigation
Ctrl+a→ Go to the beginning of the lineCtrl+e→ Go to the end of the lineAlt+f→ Move cursor to the next wordAlt+b→ Move cursor to the previous wordCtrl+x,x→ Move cursor between the current position and the begining of the line
Editing
Ctrl+k→ Cut line after cursor and copy it to the clipboardCtrl+u→ Cut line before cursor and copy it to the clipboardCtrl+y→ Paste what you have on the clipbaordCtrl+_→ Undo your last key press
Processing
Ctrl+c→ Kill the currently running commandCtrl+d→ Exit the shellCtrl+l→ Clear the screen (Same as theclearcommand)
History
Alt+p→ Search backward through the history starting at the current lineAlt+n→ Search forward through the history starting at the current lineCtrl+r→ Open the history search
Tips
Install Bash-completion
Bash-completion helps you type commands faster and easiler.
# Ubuntu
sudo apt install bash-completion
# Rocky
sudo dnf install bash-completion
Press [TAB] when you type commands, for example:
sudo git [TAB]
sudo systemctl [TAB]
History search with arrow keys
You can enable arrow keys -- [Up] for backward and [Down] for forward --
for history search by these commands (You can put them in your .bashrc.)
bind '"\e[A": history-search-backward'
bind '"\e[B": history-search-forward'
Write a file in a script
Create a new file / Overwrite an existing file
## tee
tee /tmp/test.txt <<EOF
This is the 1st line
This is the 2nd line
EOF
# cat
cat <<EOF> /tmp/test.txt
This is the 1st line
This is the 2nd line
EOF
Append new lines
# tee
tee -a /tmp/test.txt <<EOF
This is the 3rd line
This is the 4th line
EOF
# cat
cat <<EOF>> /tmp/test.txt
This is the 3rd line
This is the 4th line
EOF
I prefer using tee because tee also prints these lines to stdout.
Array in Bash script
test_array.sh
myArray=("cat" "dog" "mouse" "frog")
echo ${myArray[@]}
echo ${!myArray[@]}
for str in ${myArray[@]}; do
echo $str
done
for i in ${!myArray[@]}; do
echo "element $i is ${myArray[$i]}"
done
Make your bash script safer
#!/bin/bash
set -euxo pipefail
-e→ Exit immediately if a command exits with a non-zero status.-u→ Treat unset variables as an error when substituting.-x→ Print commands and their arguments as they are executed.-o pipfail→ The return value of a pipeline is the status of the last command to exit with a non-zero status, or zero if no command exited with a non-zero status.
Get the directory path where a script is located
#!/bin/bash
SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
echo "Script directory: $SCRIPT_DIR"