Shell Scripting Notes
Shell Scripting Notes
==
if [ <condition> ]; then
<logic>
elif [ <condition> ]; then
<logic>
else
<logic>
fi
for loop
========
while loop
==========
while [ condition ]; do
<logic>
done
string in bash
==============
test_var=10
test_var+=20
output: 1020
test_var=10
test_var=$(( test_var+=20 ))
${var}
Example:
Multiple inputs
===============
If you run this script as ./script.sh arg1 arg2 arg3, the output will be:
Number of arguments: 3
Arguments passed: arg1 arg2 arg3
Argument: arg1
Argument: arg2
Argument: arg3
Single input
============
if [ $# -ne 1 ]; then
echo "Usage: $0 <directory_path>"
exit 1
fi
target_directory="$1"
===================
func_name() {
<commands>
}
eg:
send_email() {
echo -e "$body" | mail -s "$subject" "$recipient"
}
tail -n 8 | head -n 5 # tail implies start from 8th line till end.
head will strip off first 5 lines from that.
b) using awk
To filter only one line ( or all matching lines for a keyword )from the result of a
command output
===================================================================================
===============
To sort results
===============
Example:
First identify the Field delimiter and then use it ( default is space).
awk -F ',' '{print $2}' # $1, $2 etc holds the extracted columns
3. You can use BEGIN logic to do some pre-processing ( like creating column headers
for printing the data).
Eg: top -b -n 1 | awk 'BEGIN {printf "| %-8s | %-8s | %-8s | %-8s | %-8s | %-8s |
%-8s | %-8s | %-8s | %-8s |\n", "PID", "USER", "%CPU", "%MEM", "TIME+", "COMMAND",
"PID", "USER", "%CPU", "%MEM"} NR>7 && NR<=17 {printf "| %-8s | %-8s | %-8s | %-8s
| %-8s | %-8s | %-8s | %-8s | %-8s | %-8s |\n", $1, $2, $3, $4, $5, $6, $7, $8, $9,
$10}'
SED (Stream EDitor) is a powerful command-line tool used for text manipulation in
Unix and Linux environments. It processes text line by line, applying specified
operations to the input stream (or files) and producing the modified text as
output.
Examples:
1.
sed 's/milk/soy milk/' data001.txt
# file is not directly modified. but SED keeps the modified file in
it's own space.
2. In the above case, to change all occurance of the word in a line, make the
substitution global.
5. To substitute only the words that are not part of another word; use word
boundaries (\b)
But the best way is to use extended regex where ever possible.
9. Random combination of valid strings, numbers etc and operations based on that.
eg:
# Observation: While using differnt regular expression tools like sed, awk, grep,
cut etc, you should know how each group of the result is addressed.
# In the case of awk, grep, cut etc , each group of result is stored in
$1, $2, $3 ... etc.
# In the case of sed, the results are stored in \1, \2, \3 etc. You
also need to understand, the results of any expression evaluations are only stored.
# For example, in the below sed command, there is only one regex in the
pattern to be matched. other part is just variable expansion. Hence the evaluated
result is stored in \1.
# Special characters have special meaning in shell when they are not escaped. If
they are escaped, no special meaning and treated as a string ( Exception is when
using -E with sed. Special charater meaning can be retained in this case without
using escapes )
[[ <condition ]] operation
==========================
# [[ ... ]] is newer and applicable only in shells that support them. The [[ ... ]]
construct in Bash is an extended test command. It provides additional features
compared to the [ ... ] (single square # brackets) test command, including support
for pattern matching and additional logical operators.
Examples:
=========
8. case "$variable" in
"value1")
# Code for value1
;;
"value2")
# Code for value2
;;
*)
# Default case
;;
esac
1.
#!/bin/bash
fruit="apple"
case "$fruit" in
"apple")
echo "Selected fruit is Apple"
;;
"banana")
echo "Selected fruit is Banana"
;;
"orange")
echo "Selected fruit is Orange"
;;
*) # Default case if none of the patterns match
echo "Unknown fruit"
;;
esac
2.
#!/bin/bash
score=85
case $score in
90|91|92|93|94|95|96|97|98|99|100) ( or use can use {90..100} )
echo "A"
;;
80|81|82|83|84|85|86|87|88|89)
echo "B"
;;
70|71|72|73|74|75|76|77|78|79)
echo "C"
;;
60|61|62|63|64|65|66|67|68|69)
echo "D"
;;
*)
echo "F"
;;
esac
3.
#!/bin/bash
file="example.txt"
case "$file" in
*.txt)
echo "Text file"
;;
*.jpg|*.jpeg)
echo "JPEG image"
;;
*.png)
echo "PNG image"
;;
*)
echo "Unknown file type"
;;
esac
4.
#!/bin/bash
day="Monday"
case "$day" in
"Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday")
echo "Weekday"
;;
"Saturday" | "Sunday")
echo "Weekend"
;;
*)
echo "Invalid day"
;;
esac