M3 Cheat Sheet Intro To Shell Scripting
M3 Cheat Sheet Intro To Shell Scripting
Scripting
Bash shebang
#!/bin/bash
which bash
ls | sort -r
Pipe the output of manual page for ls to head to display the first 20 lines:
Use a pipeline to extract a column of names from a csv and drop duplicate names:
set
Define a shell variable called my_planet and assign value Earth to it:
my_planet=Earth
echo $my_planet
read first_name
Tip: Whatever text string you enter after running this command gets stored as the value of the
variable first_name .
env
export my_planet
export my_galaxy='Milky Way'
Metacharacters
Comments # :
Command separator ; :
ls *.json
ls file_2021-06-??.json
Quoting
I/O Redirection
Command Substitution
THE_PRESENT=$(date)
echo "There is no time like $THE_PRESENT"
crontab -e
Run a shell script on the first minute of the first day of each month:
1 0 1 * * ./My_Shell_Script.sh
crontab -l
Conditionals
if [[ $# == 2 ]]
then
echo "number of arguments is equal to 2"
else
echo "number of arguments is not equal to 2"
fi
'or' operator || :
if [ condition1 ] || [ condition2 ]
Logical operators
Operator Definition
== is equal to
!= is not equal to
Arithmetic calculations
$(())
Symbol Operation
+ addition
- subtraction
* multiplication
/ division
Display the result of adding 3 and 2:
echo $((3+2))
Negate a number:
echo $((-1*-2))
Arrays
my_array+="six"
my_array+=7
for loops
for i in {0..5}; do
echo "this is iteration number $i"
done
Use array indexing within a for loop, assuming the array has seven elements:
for i in {0..6}; do
echo ${my_array[$i]}
done
Authors
Jeff Grossman
Sam Propupchuk
Other Contributors
Rav Ahuja
Change Log