bash

Synopsis

Bash is a powerful scripting language that is used by many developers. This cheat sheet is a collection of Bash tips and tricks that will help you write better Bash scripts.

Bash Basics

CommandDescription
echoPrint a message to the console
printfPrint a formatted message to the console
catPrint the contents of a file to the console
pwdPrint the current working directory
cdChange the current working directory
lsList the contents of a directory
mkdirCreate a new directory
touchCreate a new file
cpCopy a file or directory
mvMove a file or directory
rmRemove a file or directory
findFind files or directories
grepSearch for a string in a file
wcCount the number of lines, words, and characters in a file
sortSort the lines in a file
uniqRemove duplicate lines in a file
headPrint the first 10 lines of a file
tailPrint the last 10 lines of a file
manDisplay the manual page for a command
whichDisplay the location of a command
typeDisplay the type of a command
aliasCreate an alias for a command
historyDisplay the command history
clearClear the console
exitExit the console

Variables

CommandDescription
var="value"Assign a value to a variable
echo $varPrint the value of a variable
echo ${var}Print the value of a variable
echo "$var"Print the value of a variable
echo "${var}"Print the value of a variable
echo '$var'Print the literal value of a variable
echo '${var}'Print the literal value of a variable
echo "${var:-default}"Print the value of a variable or a default value if the variable is not set
echo "${var:=default}"Assign a default value to a variable if the variable is not set
echo "${var:?error}"Print an error message if the variable is not set
echo "${var:+value}"Print a value if the variable is set
echo "${var:offset}"Print a substring of a variable

Functions

CommandDescription
function_name() { ... }Define a function
function_name() { echo "Hello World"; }Define a function
function_name() { echo "Hello $1"; }Define a function with parameters
function_name() { echo "Hello $@"; }Define a function with parameters

Arrays

CommandDescription
array=(value1 value2 value3)Define an array
echo ${array[0]}Print the value of an array element
echo ${array[@]}Print the values of an array
echo ${#array[@]}Print the number of elements in an array
echo ${#array[0]}Print the length of an array element
array[0]="value"Assign a value to an array element
array+=(value)Append a value to an array
unset array[0]Remove an array element
unset arrayRemove an array

Conditionals

CommandDescription
if [ condition ]; then ... fiIf statement
if [ condition ]; then ... else ... fiIf/else statement
if [ condition1 ]; then ... elif [ condition2 ]; then ... else ... fiIf/elif/else statement
case value in pattern1) ... ;; pattern2) ... ;; esacCase statement
case value in pattern1) ... ;; pattern2) ... ;; *) ... ;; esacCase statement with a default case

Loops

CommandDescription
for var in value1 value2 value3; do ... doneFor loop
for var in $(command); do ... doneFor loop
for (( i=0; i<10; i++ )); do ... doneFor loop
while [ condition ]; do ... doneWhile loop
until [ condition ]; do ... doneUntil loop

Input/Output

CommandDescription
read varRead input from the console
read -p "Enter a value: " varRead input from the console with a prompt
read -a arrayRead input from the console into an array
read -dRead input from the console until a delimiter is found
read -sRead input from the console without echoing the input
read -nRead a specified number of characters from the console
read -tRead input from the console with a timeout
echo "Hello World" > file.txtRedirect output to a file
echo "Hello World" >> file.txtAppend output to a file
echo "Hello World" 2> file.txtRedirect error output to a file

Debugging

CommandDescription
set -xEnable debugging
set +xDisable debugging
set -vPrint shell input lines as they are read
set +vDo not print shell input lines as they are read
set -nRead commands but do not execute them
set +nExecute commands read from the command line

Miscellaneous

CommandDescription
echo "Hello World"Print a string
echo -n "Hello World"Print a string without a newline
echo -e "Hello\tWorld"Print a string with escaped characters

Bash Advanced

Bash Builtins

CommandDescription
.Execute a script in the current shell
sourceExecute a script in the current shell
:Do nothing
trueDo nothing
falseDo nothing
breakExit a loop
continueSkip to the next iteration of a loop
returnExit a function
exitExit the shell
setSet shell options
unsetUnset shell options
exportExport a variable
readonlyMake a variable read-only
declareDeclare a variable
typesetDeclare a variable
localDeclare a local variable
evalEvaluate a string as a command
execExecute a command
shiftShift positional parameters
waitWait for a background process to complete
pwdPrint the current working directory
cdChange the current working directory
pushdPush the current working directory onto the directory stack

Bash Options

CommandDescription
set -oList shell options
set -o noclobberDo not overwrite existing files
set -o errexitExit on error
set -o errtraceExit on error in a function
set -o nounsetExit on unset variable
set -o pipefailExit on pipe failure
set -o xtracePrint commands and their arguments as they are executed

Bash Aliases

CommandDescription
aliasList aliases
alias name="command"Create an alias
unaliasRemove an alias

Bash Functions

CommandDescription
function name { ... }Define a function
name() { ... }Define a function
declare -fList functions
declare -f nameList a function

Bash Arrays

CommandDescription
array=(value1 value2 value3)Create an array
array[0]="value"Assign a value to an array element
array+=(value)Append a value to an array
unset array[0]Remove an array element
unset arrayRemove an array
declare -aList arrays
declare -a arrayList an array
declare -pList variables
declare -p arrayList a variable

Bash Conditionals

| Command | Description | | -------------------------------- | ------------ | -------------- | ------------ | | [[ condition ]] | If statement | | [[ condition1 && condition2 ]] | If statement | | [[ condition1 | | condition2 ]] | If statement | | [[ ! condition ]] | If statement | | [[ value1 == value2 ]] | If statement | | [[ value1 != value2 ]] | If statement | | [[ value1 < value2 ]] | If statement | | [[ value1 > value2 ]] | If statement |

Bash Loops

CommandDescription
for var in "${array[@]}"; do ... doneFor loop
for (( i=0; i<10; i++ )); do ... doneFor loop
while [[ condition ]]; do ... doneWhile loop
until [[ condition ]]; do ... doneUntil loop
select var in "${array[@]}"; do ... doneSelect loop

Bash Input/Output

CommandDescription
read -p "Enter a value: " valueRead input from the console
read -p "Enter a value: " -s valueRead input from the console without echoing the input
read -p "Enter a value: " -n 5 valueRead a specified number of characters from the console

Bash Arguments

CommandDescription
$#Specifies number of arguments
$*Specifies all positional arguments as a single word
$@Specifies all positional arguments as separate words
$1Specifies first argument passed
$_Specifies last argument of the previous command