This document serves as a non-exhaustive cheat sheet for essential Bash commands on Unix. We recommend using man <command> or <command> --help for more detailed information on each command (documentation).
Note: This document includes commands that can lead to data loss, etc. This document may also contain errors. So it's crucial to refer to the official documentation before using them.
cd /home/
cd "/home/my user/"
cd /home/my\ user/ # Escaping space
cd $MY_DIRECTORY # Using a variable
cd - # Switch to the previous directory
cd # Switch to the user's home directory, same as cd ~/
Note:
ls # Displays files/directories in the current directory
ls /home # Displays files/directories in the /home directory
# The "-l" option displays in long format: access rights, owners, groups, file size... The "-a" option shows files starting with "."
ls /home -la
ls /var/log/*log # Displays all files ending with "log"
ls -F # Appends a slash to directory names
ls -lr # Lists files in reverse order
Note:
mv fileA.txt fileB.txt # Rename
mv ../myFile.txt ./ # Move the file "myFile.txt" to the current directory
mv ../myFile.txt myFolder/ # Move the file "myFile.txt" to the folder myFolder
mv myFolder myFolder2 # Rename myFolder to myFolder2
mv myFolder2/* ../ # Move all contents (*) of the folder myFolder2 to the parent folder (../)
cp myFile myFolder/ # Simple file copy
cp myFolder/* myFolder2/ # Copy folder contents to another
cp -r myFolder/ myFolder3/ # Copy myFolder to myFolder3 using the -r (recursive) option
The touch command updates the access and modification time of one or more files to the current time. If the file does not exist, it creates an empty file.
touch myFile.txt
Also, with stream redirection:
> myFile.txt # Creates the file if it doesn't exist. Warning, it empties it if it exists!
true > myFile.txt # same as above
>> myFile.txt # Creates the file if it doesn't exist, does not modify its content or date if it exists.
echo "AAA" > myFile.txt # Creates the file if it doesn't exist. Puts "AAA" inside.
rm myFile.txt # Delete a file in the current directory
rm *.log # Delete all files ending with .log in the current directory
rm -r myFolder/ # Delete a folder (recursive)
rm -rf myFolder/ # Delete a folder with the "force" option. Therefore, no confirmation will be asked for certain folders (use with caution)
cat myFile.txt # Display file contents
cat -n myFile.txt # Display file contents with line numbers
cat *.log # Display all contents of files ending with log
Displays the first 10 lines of the file
head myFile.txt # Display the first 10 lines
head -n 5 myFile.txt # Display the first 5 lines
head -n -5 myFile.txt # Display all except the last 5 lines
head -n -5 myFile1.txt myFile2.txt # Display all except the last 5 lines of myFile1.txt, then myFile2.txt
tail myFile.txt # Display the last 10 lines
tail -n 5 myFile.txt # Display the last 5 lines
tail -n +5 myFile.txt # Display all except the first 5 lines
tail -n +5 myFile1.txt myFile2.txt # Display all except the first 5 lines of myFile1.txt, then myFile2.txt
more myFile.txt # Paginated display
less myFile.txt # For large files
myCommand
myCommand & # Command executed in the background
myCommand1; myCommand2; # Commands executed sequentially
Logical operators && (and) and || (or) allow conditional execution of commands
# myCommand1 && myCommand2;
# Execute myCommand1 then myCommand2 if myCommand1 succeeds
mkdir myFolder && touch myFolder/myFile.txt
# myCommand1 || myCommand2;
# Execute myCommand1 then myCommand2 if myCommand1 fails.
mkdir myFolder || echo "KO"
# myCommand1 && myCommand2 || myCommand3;
# Execute myCommand1 then myCommand2 if myCommand1 succeeds.
# If myCommand1 or myCommand2 fails, then execute myCommand3.
mkdir myFolder && echo "OK" || echo "KO"
Note: To check if a command fails, you can display the content of the $? variable after executing the command. It returns 0 if the command executed successfully, otherwise another value.
mkdir myFolder
echo $? # Output: 0 => success
mkdir myFolder # Output: mkdir: cannot create directory ‘myFolder ’: File exists
echo $? # Output: 1 => error because the folder already exists
Each process has by default:
Called "pipe", the pipe mode ("|") redirects the output of one command to the input of another command. Here, from myCommand1 to the input of myCommand2:
myCommand1 | myCommand2
Redirecting to a file:
# Only redirect the standard output (stdout 1) to myFile.txt
myCommand > myFile.txt
# Read the file myFile and send the initial read content to the standard output to the file myFile2.txt (creates or empties myFile2.txt if it exists)
cat myFile > myFile2.txt
# Similar to the previous command, but appends to the file (does not empty the file before reading).
myCommand >> myFile.txt
# Redirect errors to the file (creates or empties the errorFile.log if it exists)
myCommand 2> errorFile.log
mkdir myFolder 2> errorFile.log
# Similar to the previous command, but appends to the file (does not empty the file before reading).
myCommand 2>> errorFile.log
Tools:
# Never use or see the error output, so redirect it to dev/null
myCommand 2>/dev/null
# Have no output
myCommand > /dev/null 2>&1
# Redirect the error output to the same file as the standard output
myCommand > myFile.log 2>&1
Redirecting the standard input with < or <<. The keyword following "<<" must appear on a new line containing only that keyword to signify the end of the standard input for the specified command.
myCommand << KEYWORD TEXT
TEXT
KEYWORD
echo << END "AAA"
END # Output: AAA
# Redirect the input contained in myFile.txt to myCommand
myCommand < myFile.txt
ps # Lists user processes
ps -A # Lists all processes
top # Lists all processes and their load, more visual than ps
htop # Like top, but more readable (package to install)
kill PID # Stop a process by its PID
kill -9 PID # Sends the SIGKILL signal to the process (force stop)
killall NAME # Stop a process by its name
Basic declaration: VARIABLE_NAME="VALUE" or VARIABLE_NAME='VALUE':
age=30
firstName="Alex"
firstName='Alex'
Usage example:
echo "My name is $firstName, I am ${age} years old."
# Output: My name is Alex, I am 30 years old.
# Also works to display only the variable content
echo $firstName
echo ${age}
To display a variable, you can use the $VARIABLE_NAME syntax, or ${VARIABLE_NAME} (best practices)
Note:
Other useful declaration forms:
# Read-only
readonly lastName="Brown" # or declare -r
# Declare a variable as an integer
declare -i age=30
To delete a variable, you need to use the unset command.
unset firstName;
echo "My name is $firstName, I am ${age} years old."
# Output: My name is , I am 30 years old.
When declared, by default, a variable is only visible in its current environment. It can also be local (scoped within a function) using the keyword "local", or have a more global visibility (visible in the entire environment) using the keyword "export":
firstName="Alex" # visible in the current exec environment
local firstName; # Locally visible (for example in a function)
export firstName; # Globally visible (in the entire environment)
Example:
function test() {
local firstName;
firstName="Alex";
echo $firstName;
}
firstName="Claire";
echo $firstName; # Output: Claire
test; # Output: Alex
echo $firstName; # Output: Claire
Generally, note that there are spaces at the beginning and end of the operation closures. Without them, you will get an error.
result=$(( (10 * 5) + 3 ))
result=$[ (10 * 5) + 3 ]
Also see the let function.
Useful in scripts:
Useful at the end of a command/script execution:
Generally useful:
Also see the env function.
As seen previously, to list a file containing a space, we had to put the character \ before the space. Without it, we would have had an error. Several characters called "special" are not interpreted in the same way. The space would have meant that there was a second argument (cd /home/my\ user/). Similarly, the *, which means "all" (cat *.log).
Examples with the star:
echo He saw a * # Output: He saw a fileA.txt fileB.txt fileC.txt
The special characters that need to be escaped are generally the following: ", ', `, \, $, !, ?, ~, (), [], {}, @, *
They can be escaped with a \, be enclosed in ' or ":
echo "He saw a *" # Output: He saw a *
echo 'It works!' # Output: It works!
echo "It works too!" # Output: It works too!
echo This\ also\ works\ \! # Output: This also works!
# Escaping also within " "
echo "My path is $PATH and my shell is $SHELL" # Will replace variables $...
echo "My path is \$PATH and my shell is \$SHELL" # Will not replace variables $
echo 'My path is $PATH and my shell is $SHELL' # Will not replace variables $, same as the previous command
myString="Alex" # the variable contains "Alex"
myString=$(ls /) # the variable contains the listing of the root directory (/)
myString=`ls /` # the variable contains the listing of the root directory (/). Obsolete.
commands / Parameter |
variable set and not null | variable set and null | variable unset | |
Using default values |
${variable:-alternative} |
returns variable | returns variable | returns alternative |
${variable-alternative} |
returns variable | returns null | returns alternative | |
Assigning default values |
${ variable:=alternative} |
returns variable | assignment, returns alternative | assignment, returns alternative |
${variable=alternative} |
returns variable | returns null | assignment, returns alternative | |
Error indication |
${variable:?alternative} |
returns variable | error, exit | error, exit |
${variable?alternative} |
returns variable | returns null | error, exit | |
Using alternative |
${variable:+alternative} |
returns alternative | returns null | returns null |
${variable+alternative} |
returns alternative | returns alternative | returns null |
Examples:
# Help to retrieve a default value if not defined => ":-"
echo ${VARIABLE1-$VARIABLE2} => if VARIABLE1 is not defined or empty, $VARIABLE2 returned
${VARIABLE1-'text'} => if VARIABLE1 is not defined or empty, 'text' will be returned
# Help to retrieve a default value if not defined and not empty => ":-"
echo ${VARIABLE1:-$VARIABLE2} => if VARIABLE1 is not defined and is not empty, $VARIABLE2 will be returned
${VARIABLE1:-'text'} => if VARIABLE1 is not defined or empty and is not empty, 'text' will be returned
# Help to assign a variable if not defined and not empty => ":="
echo ${VARIABLE1=$VARIABLE2} => if VARIABLE1 is not defined, $VARIABLE2 will be returned and VARIABLE1 will have the value of $VARIABLE2
${VARIABLE1='text'} => if VARIABLE1 is not defined or empty, 'text' will be returned and assigned to VARIABLE1
# Help to assign a variable if not defined and not empty => ":="
echo ${VARIABLE1:=$VARIABLE2} => if VARIABLE1 is not defined and is not empty, $VARIABLE2 will be returned and VARIABLE1 will have the value of VARIABLE2
${VARIABLE1:='text'} => if VARIABLE1 is not defined or empty and is not empty, 'text' will be used
# Error if the variable is not defined => "?" and ":?"
VARIABLE1=""
${VARIABLE1?"Variable is not set"} # bash: VARIABLE1: Variable is not set
unset VARIABLE1
${VARIABLE1:?"Variable is not set or empty"} # bash: VARIABLE1: Variable is not set or empty
Command | Summary |
${#variable} | Returns the length of the variable |
${variable:X} | Retrieves a substring after the Xth character |
${variable:-X} | Retrieves the last X characters |
${variable:X:Y} | Retrieves a substring after the Xth character for a length of Y |
${variable::X} | Retrieves the first X characters |
${variable::-X} | Retrieves all characters except the last X |
${variable#pattern} | Retrieves all characters by removing from the beginning of the string the portion matching the pattern |
${variable##pattern} | Retrieves all characters by removing from the beginning of the string the longest portion matching the pattern |
${variable%pattern} | Retrieves all characters by removing from the end of the string the portion matching the pattern |
${variable%%pattern} | Retrieves all characters by removing from the end of the string the longest portion matching the pattern |
${variable,,} | Returns the variable in lowercase |
${variable^^} | Returns the variable in uppercase |
Examples:
firstName="Alexandre"
echo "String length ${#firstName}" # Output: String length 9
echo "Cut the string: ${firstName:4}" # Cut the string: andre
echo "${firstName: -3}" # dre
echo "Cut the string to a fixed length: ${firstName:4:3}" # Cut the string to a fixed length: and
echo "Cut the string to a fixed length: ${firstName:4:30}" # Cut the string to a fixed length: andre
echo "${firstName::3}" # Ale
echo "${firstName::-3}" # Alexan
myText="The development was completed correctly this morning. This development took 30 minutes."
echo ${myText#The*o} # Output: pment was completed correctly this morning. This development took 30 minutes.
echo ${myText##The*o} # Output: k 30 minutes.
echo ${PWD%/*}
echo ${myText%% *} # Output: The
# Convert to lowercase
echo ${myText,,}
# Convert to uppercase
echo ${myText^^}
Command | Summary |
${variable/AA/BB} | Returns the value of the variable with the first occurrence of AA replaced by BB |
${variable//AA/BB} | Returns the value of the variable with all occurrences of AA replaced by BB |
Examples:
myText="The development was completed correctly this morning. This development took 30 minutes."
# Replace development with integration (first occurrence)
echo ${myText/development/integration}
# Output: The integration was completed correctly this morning. This development took 30 minutes.
# Replace development with integration (all occurrences)
echo ${myText//development/integration}
# Output: The integration was completed correctly this morning. This integration took 30 minutes.
Concrete example:
file="/etc/log/log.txt"
fileName="log.txt"
# Extract the path
echo ${file%/*} # /etc/log/
# Extract the file
echo ${file##*/} # log.txt
# Extract the file without the extension
echo ${fileName%.*} # log
# Extract the file extension
echo ${fileName##*.} # txt
Bash scripts have a .sh file extension (although this is optional). These scripts have the first line #!/bin/bash (shebang), which allows defining with what the script will be interpreted (here bash).
List of argument variables:
To add parameters by automatically updating $1 etc, use the set command, example:
set alex 21
Useful standard variables:
A bash script has a default exit value of 0, which is conventionally a success exit. It is possible to exit with a failure, using the exit command. The exit code can range from 0 to a maximum of 255 inclusive.
exit 25;
The recovery of this value is done via the $? variable. Let's take for example "myScript.sh which does an "exit 25;" only:
./myScript.sh
echo "Error code: $?"; # Output: Error code: 25
echo "Error code: $?"; # Output: Error code: 0
Note: We can see that the second "echo" returns "0" as the error code, because "$?" returns the error code of the last executed command => here the previous "echo" which correctly displayed "Error code: 25".
To include a bash script in another, it must be executed. Example:
my_dir="/your/path"
"$my_dir/other_script.sh"
To avoid having everything in the same block, bash allows creating functions.
# Function without arguments
function example {
echo "Hello";
}
# Function with 2 arguments
function example2 {
echo "Hello $1 and $2, I have $# arguments";
echo "Here are all my arguments: $*";
echo "Or: $@";
}
myVariable=$(example) # You can store the output of a function in a variable
echo $myVariable # Output: Hello
example2 A B # Note: Calls are made without parentheses or commas to separate arguments. A space is enough.
# Output:
# Hello A and B, I have 2 arguments
# Here are all my arguments: A B
# Or: A B
# Get the function declaration
declare -f example2
#Output
#example2 ()
#{
# echo "Hello $1 and $2, I have $# arguments";
# echo "Here are all my arguments: $*";
# echo "Or: $@"
#}
Arrays (indexed arrays => integer keys) work almost the same as dictionaries (like maps: associative arrays => integer/string keys).
Action / Type | Array | Dictionary |
Declaration |
declare -a myArray | declare -A myDict |
Initialization |
myArray=( 30 Alex ) myArray=( [0]=30 [10]=Alex ) |
myDict=( [age]=25 [10]=Alex ) |
Display |
echo $myArray[0] echo ${myArray[0]} |
echo $myDict[30] echo $myDict[age] echo ${myDict[age]} |
Display all * |
echo ${myArray[*]} echo ${myArray[@]} |
echo ${myDict[*]} echo ${myDict[@]} |
Size | ${#myArray[*]} | ${#myDict[*]} |
Element size | ${#myArray[0]} | ${#myDict[age]} |
Index list | ${!myArray[*]} | ${!myDict[*]} |
Note * : [@] or [*] : prefer [@] within quotes to keep the true values (distinguish spaces from another element). Without quotes, they behave the same, but with quotes, [*] will return everything as a single word and [@] will return each element as a distinct word.
There are several ways to implement a condition (spaces are important):
if [ $MY_VARIABLE -gt 2 ] ; then # If MY_VARIABLE greater than > 2
echo "YES"
fi
if [ $# -lt 2 ] ; then
echo "YES"
else
echo "NO"
fi
if [ $# -gt 2 ] ; then
echo "YES"
elif [ $# -eq 0 ] ; then # else if
echo "MAYBE"
else
echo "NO"
fi
# It is possible to perform a test with the test command and []
if test $MY_VARIABLE -gt 2 ; then # If MY_VARIABLE greater than > 2
echo "YES"
fi
Comparators:
Type | operator | Description | Example |
Arithmetic | -eq | equals | if [ "$a" -eq "$b" ] |
-ne | not equal to | if [ "$a" -ne "$b" ] | |
-gt | greater than | if [ "$a" -gt "$b" ] | |
-ge | greater than or equal to | if [ "$a" -ge "$b" ] | |
-lt | less than | if [ "$a" -lt "$b" ] | |
-le | less than or equal to | if [ "$a" -le "$b" ] | |
< | less than | (("$a" < "$b")) | |
<= | less than or equal to | (("$a" <= "$b")) | |
> | greater than | (("$a" > "$b")) | |
>= | greater than or equal to | (("$a" >= "$b")) | |
String | = | equals (string) | if [ "$a" = "$b" ] |
== | equals (string, be careful) | if [ "$a" == " ;$b" ] | |
!= | not equal to (string) | if [ "$a" != "$b" ] | |
< | less than (ASCII) | if [[ "$a" < "$b" ]] if [ "$a" \< "$b" ] |
|
> | greater than (ASCII) | if [[ "$a" > "$b" ]] if [ "$a" \> "$b" ] |
|
-z | string is null or has a length of 0 | [ -z "$a" ] | |
-n | string is not null and has a length > 0 | [ -n "$a" ] | |
File | -e | file exists | [ -e "$a" ] |
-d | directory exists | [ -d "$a" ] | |
-r | file is readable | [ -r "$a" ] | |
-o | you are the owner of the file | [ -o "$a" ] | |
-x | file is executable | [ -x "$a" ] |
To combine tests, you can use the operators && and || with double brackets, -a (for and) and -o (for or) with single brackets.
It is generally used to manage program parameters.
Example:
while [[ $# -gt 0 ]]
do
key="$1"
case $key in
-a1|--argument1)
ARGUMENT1="$2"
shift # past argument
shift # past value
;;
-a2|--argument2)
ARGUMENT2="$2"
shift 2 # past 2 argument
;;
--a3)
a3=YES
shift # past argument
;;
--help)
echo "how to use : ....";
//exit ;
shift # past argument
;;
*) # unknown option
echo "Error in argument with $1"
//exit 1
shift # past argument
;;
esac
done
Note: The shift command shifts the arguments to the left. The value of $1 <= $2, $2 <= $3, and so on. Therefore, $# is also decremented.
firstName1="Alex";
firstName2="Claire";
firstName3="Angel";
# With a list
for firstName in $firstName1 $firstName2 $firstName3; do
echo $firstName;
done
# Output:
# Alex
# Claire
# Angel
# With a command output
for item in $(ls); do
echo item: $item;
done
# Output:
# item: fileA.txt
# item: fileB.txt
# item: fileC.txt
# item: folderA
# With a command output #2 (number sequence)
for i in $(seq 1 5); do
echo $i;
done
# Output:
# 1
# 2
# 3
# 4
# 5
# Loop with iteration
for ((it=0; it<= 5; it++)); do
echo $it;
done
# Output:
# 0
# 1
# 2
# 3
# 4
# 5
declare -a myArray;
myArray=( Alex Claire Angel );
for firstName in "${myArray[@]}"
do
echo "${firstName}"
done
# Output:
# Alex
# Claire
# Angel
it=0;
while [ $it -lt 5 ] ; do
echo "it : ${it}";
it=$(( $it + 1 )) # equivalent to ((it++))
done
# Output:
# it : 0
# it : 1
# it : 2
# it : 3
# it : 4
while :
do
read -p "Enter your age: " age # Reads from standard output
echo "You are ${age} years old";
if [ ${age} -ge 100 ] ; then
echo "You are old";
break;
else
echo "You are not old enough"
fi
echo "I won't leave until I meet someone who is 100 years old or older.";
done
# Output:
# Enter your age: 30
# You are 30 years old
# You are not old enough
# I won't leave until I meet someone who is 100 years old or older.
# Enter your age: 101
# You are 101 years old
# You are old
# Read a file line by line
while read LINE; do
echo $LINE;
done < file.txt
# Output:
# Content of the first line
# Content of the second line
# Content of the third and last line of the file.
Command | Arguments | Purpose |
basename | pathToFile | Displays the file name |
chmod |
file(s)/directory(ies) |
File access permissions |
chown |
file(s)/directory(ies) |
Change the owner and group associated with the file/directory |
cut |
<col> <file>
|
Extracts one or more columns from a file. Example:
|
date | '+%Y-%m-%d %H:%M:%S.%N' | Displays the date: 2020-01-31 22:30:46.900886000 |
'+%A %d-%B, %Y' | Another format | |
diff | file1 file2 | Displays the differences between file1 and file2 |
dirname | pathToFile | Displays the file path |
du |
|
Disk usage statistics. Displays the files and directories (recursively) in the current directory and their associated sizes. (Example: du --count-links --dereference --human-readable --max-depth=1) |
df | -h (human readable): Improves readability of file sizes | Amount of space used by the file systems. |
find |
directory
|
Searches for files or directories that meet the parameters. Example: find / -type f # Searches all files in the system. |
grep |
pattern file/directory
|
Searches files for the pattern in the given file or directory |
kill | -9 PID | Kill the process with the pid PID (SIGKILL) |
killall | name | Kill the processes with the given name |
ln | file1 file2 | Physical link from file1 to file2 |
locate | myFile.txt | Locates the location of "myFile.txt" |
man | command | Displays the manual for the command |
ps | aux | Lists processes (See top/htop) |
read | a b c |
Reads standard input. Here, waits for 3 data, example A\ A b C ==> $a = "A A", $b = b, $c = C |
sort | -r (reverse): descending | Sorts lines (default alphabetical order) |
-n: compares according to the numerical value of the string | ||
tar | -cf dest.tar source | Create an archive |
-xf archive.tar | Unarchive | |
-xf archive.tar -C /tmp | Unarchive in the /tmp directory | |
-czvf dest.tar.gz source | Create and compress an archive | |
-xvzf archive.tar.gz | Unarchive and decompress | |
-xvzf archive.tar.gz -C /tmp | Unarchive and decompress in the /tmp directory | |
time | myScript.sh | Displays the time used by the script |
tr | list1 list2 | Replaces list1 with list2 from standard input and outputs to standard output. list1 and list2 are lists of characters. |
-d: deletes the characters in list1 | ||
-s: deletes repeated characters in list1 | ||
uniq | -d: keeps only duplicate lines | Keeps only one occurrence of duplicate lines (distinct) (cat file.txt | uniq) |
-c: prefixes lines with their number of occurrences | ||
-i: ignores case | ||
-u: keeps only unique lines | ||
wc | -l (Line) -c(Character) -w (Word) | Counts the number of lines, words, or characters in a text (cat file.txt | wc -l) |
which | myCommand | locates the file containing myCommand |
zip / unzip | zip or unzip |
Shortcuts | Purpose |
ctrl + z + write bg |
Move the active task to the background Reverse command: jobs, fg%JobNum |
ctrl + c | Sends the SIGTERM signal (closes the process) |
ctrl + z | Freezes the process |
ctrl + l | Same action as the "clear" command |
ctrl + d | Writes EOF (End Of File) from the keyboard. |
ctrl + r | Searches the command history (See history) |
!myCommand | Executes the last command starting with myCommand |
LauLem.com - (Pages in French) Conditions of Use - Legal Information - Cookie Policy - Personal Data Protection Policy - About