Bash Shell Scripting Presentation
Bash Shell Scripting Presentation
Scripting
By:
Dr. Basharat Mahmood
Dr. Madiha Yousuf
• Definition:
• Bash (Bourne Again SHell) is a Unix shell and
command language.
• History:
• Developed by Brian Fox for the GNU Project as a
free software replacement for the Bourne shell.
• Significance:
• Default shell on many Linux distributions and
macOS.
• Automation:
• Automates repetitive tasks, saving time and
reducing errors.
• Efficiency:
• Streamlines processes, making workflows faster
and more efficient.
• System Administration:
• Essential for managing Linux systems and
servers, performing tasks like backups, updates,
and monitoring.
High Impact Training, 2024.
Basic Rules of Bash Scripting
• File Extensions:
• Scripts typically use .sh extension, e.g., script.sh.
• Shebang:
• Start scripts with #!/bin/bash to specify the script
interpreter.
• Comments:
• Use # to add comments for clarity.
• Example: # This is a comment
• Permissions:
• Make scripts executable using chmod +x script.sh.
• Basic Syntax:
• Commands are written as they are executed in the terminal.
• Whitespace:
• Important for readability, although not always syntactically
necessary.
• Semicolons:
• Used to separate multiple commands on a single line.
• Example: echo "Hello"; echo "World"
• echo:
• Prints text to the terminal.
• Example:
echo "Hello, World!"
• read:
• Reads input from the user.
• Example:
read -p "Enter your name: " name
echo "Hello, $name"
• printf:
• Formats and prints text.
• Example:
printf "Name: %s\n" "$name"
High Impact Training, 2024.
Using Linux Commands in Scripts
• Example Commands:
• ls, pwd, cd, cp, mv, rm
• Integration:
• Example:
echo "Current Directory:"
pwd
echo "Listing Files:"
ls
• Creating Variables:
• Example:
name="John"
age=25
• Using Variables:
• Example:
echo "Name: $name"
echo "Age: $age"
• Syntax:
• Example:
for i in {1..10}; do
echo $i
done
• Example:
for file in *.txt; do
echo "Processing $file"
done
• Syntax:
while [ condition ]; do
# statements
done
• Example:
count=1
while [ $count -le 5 ]; do
echo $count
((count++))
done
• Syntax:
until [ condition ]; do
# statements
done
• Example:
count=1
until [ $count -gt 5 ]; then
echo $count
((count++))
Done
• Creating Arrays:
• Example:
array=(1 2 3 4 5)
• Accessing Elements:
• Example:
echo ${array[0]}
• Iterating:
• Example:
for i in "${array[@]}"; do
echo $i
done
• Defining Functions:
• Example:
function greet() {
echo "Hello, $1"
}
• Calling Functions:
• Example:
greet "John"
• Accessing Arguments:
• Example:
echo $1 $2
• Special Variables:
• $#: Number of arguments
• $@: All arguments
• $*: All arguments as a single string
• Example:
echo "Number of arguments: $#"
echo "All arguments: $@"
• Concatenation:
• Example:
str="Hello"
str+=" World"
echo $str
• Slicing:
• Example:
echo ${str:0:5}
• Length:
• Example:
echo ${#str}
• Common Variables:
• PATH, HOME, USER, SHELL
• Using Environment Variables:
• Example:
echo $HOME