Intro To Bash Scripting
Intro To Bash Scripting
Bash Programming
• Bash Programming Language can perform basic arithmetic operations.
• Create a new file named math.sh in ~/ directory.
• Open the file in your preferred text editor.
• Type the following code into math.sh:
%%sh
#!/usr/bin/env bash
# File: math.sh
expr 5 + 2
expr 5 - 2
expr 5 \* 2
expr 5 / 2
Bash Programming
• Save the file and run the script in your shell:
%%sh
bash math.sh
• Expected Output:
7
3
10
2
• Explanation:
• Bash executes programs line by line.
• expr evaluates Bash expressions.
• Arithmetic operators (+, -, *, /) work as expected.
• Use \* to escape the multiplication operator.
Variables
• Variables in Bash can store data.
• Naming conventions for variables:
• Lowercase letters.
• Start with a letter.
• Alphanumeric characters and underscores.
• Words separated by underscores.
1
• Example of variable assignment:
%%sh
chapter_number=5
Variables
• Print the value of a variable:
%%sh
echo $chapter_number
%%sh
let chapter_number=$chapter_number+1
%%sh
the_empire_state="New York"
• Command substitution:
%%sh
math_lines=$(cat math.sh | wc -l)
echo $math_lines
%%sh
#!/usr/bin/env bash
# File: vars.sh
User Input
• read command: Accept user input in scripts.
• Example script using read:
2
%%sh
#!/usr/bin/env bash
# File: letsread.sh
%%sh
if [ condition ]; then
# code block
else
# code block
fi
%%sh
#!/usr/bin/env bash
# File: ifelse.sh
%%sh
#!/usr/bin bash
num1=7
num2=12
num3=9
References
• https://seankross.com/the-unix-workbench/