Shell Notes
Shebang
#!/bin/bash
- It tells the system to use
/bin/bash
as the interpreter for this scriptVariables
- Can contain a number, a character or a string.
- Can contain ‘_’.
- Case sensitive.
- Value assignment through ‘=’. No space permitted between =.
- eg.
name='Kush' age=26 h_w='Hello World'
((...))
tells Bash to interpret the expression as arithmetic operationa=1 b=4 echo $((a+b))
- ’ \ ‘ is used to escape special character meaning.
PRICE_PER_APPLE=5 echo "The price of an Apple today is: \$HK $PRICE_PER_APPLE"
Output : The price of an Apple today is: $HK 5
-
”${}” is used to avoid ambiguity.
-
`` can assign a command’s output to a variable eg.
FILELIST=`ls`
Use of $
- access value of a variable
echo "hello, $name"
- execute a command
$(command)
- performing arithmetic operations
$((a+b))
- positional reference
$1 $2
Passing Arguments to the Script
- Inside the script, the $1 variable references the first argument in the command line, $2 the second argument and so forth.
- The variable $0 references to the current script.
eg.
#!/bin/bash
echo "Current file :"$0
echo "Name : $1"
echo "Age : $2"
Output : user1:~$ ./temp.sh Kush 20
Current file :./temp.sh
Name : Kush
Age : 20
-
The variable
$#
holds the number of arguments passed to the script -
The variable
$@
holds a space delimited string of all arguments passed to the script
Arrays
my_array=(apple banana "Fruit Basket" orange)
echo ${#array[@]}
: given the size of the array (4)-
``echo ${my_array[3]}` : orange
my_array[4]="carrot"
: value assignment without a $ and curly bracketsecho ${#my_array[@]}
: 5echo ${my_array[${#my_array[@]}-1]}
: carrot
Piping
|
- used to pass the output of one command as input to another command. This allows you to chain commands together efficiently.
- Syntax :
command1 | command2 | command3
ls -l | grep "txt"
ls -l
lists files in long format.grep "txt"
filters the list to show only files containing “txt” in their names.- List Files and Search for a Pattern
Output Redirection
>
write to a file>>
append to a file
Input Redirection
<
redirects input from a filecat > file.txt
=cat file.txt
cat > file.txt
- Bash opens file.txt for reading.
- It redirects the content of file.txt into cat as if you typed it from the keyboard.
- cat reads from standard input (stdin) and prints it.
<<
redirects a block of text as input- Syntax :
command <<EOF text line 1 text line 2 EOF
<<<
redirects a single string as inputcat <<< "Hello, World!"
o/p Hello, World!
wc
- Syntax :
wc [options] [file]
- options :
-l
count lines-w
count words
wc -w < textfile.txt
o/p = 3wc -w <<< "hello world I am Kush"
o/p = 6
if, elif, else statement
#!/bin/bash
if [ ${1,,} = kush ]; then
echo "welcome"
elif [ ${1,,} = help ]; then
echo "enter your username"
else
echo "I don't know you"
fi
[ ]
= test command- use
-gt , -eq , -lt , [...] && [...]
$a , $b
are used because a and b are treated like string
- use
${1}
= first command line argument${1,,}
= converts the argument to lowercasefi
to close the if block((...))
can be used for numeric comparisions- this allows use of
< , > , = , && can be used inside the parenthesis
-
a and b can be used without $ because they are treated like variables
- this allows use of
=
is used for comparing string-eq
is used for numbers
CASE
#!/bin/bash
case ${1,,} in
kush | administrator)
echo "hello"
;;
help)
echo "enter username"
;;
*)
echo "enter valid username"
esac
|
is used as OR;;
is used to close a casexyz)
‘ ) ‘ is used to end a case name*)
= wildcard- it matches anything not covered above
esac
is used to close case block
Arrays
names=("Bob" "Peter" "$USER" "Big Bad John")
names=([0]="Bob" [1]="Peter" [20]="$USER" [21]="Big Bad John")
names=()
creates empty arrayecho ${names[@]}
prints the contentecho ${names}
prints only the first element- ` echo ${names[3]}` prints element at index 3
- 0 indexing
### Associative Array
- Like map in C++ or hashmap in java
declare -A freq
for num in "${arr[@]}" do ((freq[$num]++)) done
- To print
for key in "${!freq[@]}" do echo "$key: ${freq[$key]}" done
- Input array :
read -a arr
for loop
#!/bin/bash
names=(one two three four five six)
for item in ${names[@]}; do
echo $item | wc -c
done
- prints the size of each word in the array
Functions
#!/bin/bash
up="before"
since="function"
echo $up
echo $since
showuptime(){
local up=$(uptime -p | cut -c4-)
local since=$(uptime -s)
cat << EOF
----
this machine has been up for ${up}
It has been running since ${since}
----
EOF
}
showuptime
echo $up
echo $since
local <varname>
allows to use a variable locally in a function without altering the global variable
while loop
while [ condition ]; do
# commands to execute
done