Fast Ways to Become Proficient in Bash Scripting for Server Administration

Quick Methods to Master Bash Scripting for Managing Servers

ยท

5 min read

Fast Ways to Become Proficient in Bash Scripting for Server Administration

Prerequisites:

  • Basics of Linux

Let's start by looking at the basics of scripting in Linux:

Note: You can use any Linux distribution; I use CentOS for my projects.

A scripting file, also known as a script, is a text file filled with commands or instructions that a scripting language interpreter or runtime environment runs. Scripting languages are advanced programming languages made to automate tasks, work with other software, or carry out different operations.

In the world of automation and system administration, scripting simplifies tasks, automates repetitive actions, and enhances efficiency, with Bash (Bourne Again Shell) standing out for its power and popularity on Unix-like systems such as Linux.

1. Setting Up: First, make sure Bash is installed on your system, as most Unix-like systems already have Bash pre-installed, and you can verify the installed Bash version by running a specific command.

bash --version

2. Creating Your First Script: To begin with a simple Bash script, open your preferred text editor, create a new file named hello.sh, and add the necessary lines to it.

#!/bin/bash
# This is a simple Bash script
echo "Hello, World!"
  1. Save the file and make it executable using the following command:
chmod +x hello.sh
  1. Now, you can execute the script:
./hello.sh
  1. You should see the output:
Hello, World!

Create a new file named hello.sh in your preferred text editor, add #!/bin/bash, # This is a simple Bash script, and echo "Hello, World!" to it, save the file, make it executable with chmod +x hello.sh, and execute it with ./hello.sh to see "Hello, World!" as the output, demonstrating basic scripting.

Let's explore the syntax for a scripting file. Here are several simple examples to help you get familiar with scripting:


#Take Some input from user using read:-
echo "Hello, Enter your name, please."
read name
echo "Hi ${name}, please enter your age."

----

#Take Some input from user and wait using sleep:-
read age
echo "Hi ${name}, your age is ${age}"
sleep 2
echo "Thanks for your input ${name}."

----

#Example of if/else
if [ "$1" = "suraj" ]
then
 echo "Hey $1"
else
 echo "Hey random person"
fi

----

#Example of nested if/else
a=100
b=1000
c=10

if [[ $a -gt $b && $a -gt $c ]]
then
 echo "A is biggest"
elif [[ $b -gt $a && $b -gt $c ]]
then
 echo "B is biggest"
else
 echo "C is biggest"
fi

----

#Example of Foreach-loop
for ((i=0; i<10; i++))
do
rs=`expr $i % 2`
if [ $rs != 0 ]
then
echo "$i"
else
 echo "even"
fi
done

Now that you understand the basics of scripting, let's explore some advanced scripting concepts that will be helpful on your journey.

1. Regular Expressions:

# Check if a filename starts with "log_"
if [[ $filename =~ ^log_ ]]; then
  echo "File starts with 'log_'"
fi

# Search for lines containing "error" in a file
grep 'error' system.log
  1. Arrays:
# Create an array of names
names=("Alice" "Bob" "Charlie")

# Access the second element
echo "Second name: ${names[1]}"

# Loop through the array
for name in "${names[@]}"; do
  echo "Hello, $name"
done
  1. String Manipulation:
# Extract the first 3 characters of a variable
name="JohnDoe"
first_chars=${name:0:3}
echo "First 3 characters: $first_chars"

# Concatenate two strings
fullname="$name Smith"
echo "Full name: $fullname"

# Check if a string contains a substring
if [[ $message =~ "success" ]]; then
  echo "Message contains 'success'"
fi
  1. Here Documents:
# Create a configuration file
cat <<EOF > config.txt
# Database settings
host=localhost
user=myuser
password=secret
EOF

# Create a command with multi-line arguments
cat <<'COMMAND' | command_to_run
argument1
argument2
with
newlines
COMMAND
  1. Process Substitution:
# Search for errors in the last 10 lines of a log using process substitution
errors=$(grep 'error' <(tail -n 10 system.log))
if [[ -n "$errors" ]]; then
  echo "Found errors in the log"
fi
  1. Functions with Arguments:
# Function to calculate average of two numbers
calculate_average() {
  local sum=$(( $1 + $2 ))
  local average=$(( sum / 2 ))
  echo "Average: $average"
}

# Call the function with arguments
calculate_average 10 20
  1. Command Substitution:
# Get the current date in a specific format
current_date=$(date +%Y-%m-%d)
echo "Today's date: $current_date"

# Get the number of lines in a file
num_lines=$(wc -l < filename.txt)
echo "Number of lines: $num_lines"
  1. Advanced Conditional Statements:
# Case statement to check user choice
choice="y"
case $choice in
  "y" | "Y") echo "Yes selected";;
  "n" | "N") echo "No selected";;
  *) echo "Invalid choice";;
esac

# Check if a number is even or odd using boolean operators
number=15
if [[ $(( number % 2 )) -eq 0 ]]; then
  echo "Even number"
else
  echo "Odd number"
fi
  1. Subshells:
# Temporarily source a configuration file
(source config.sh; echo "Variable from config: $MY_VAR")

# Run a command in a subshell to avoid affecting the main script's environment
(rm -rf temporary_files; echo "Temporary files removed")
  1. I/O Redirection and Pipes:
# Redirect the output of a command to a file
ls -l > directory_listing.txt

# Pipe the output of one command as input to another
cat file1.txt | grep 'pattern' > results.txt

# Append the output of a command to an existing file
echo "Additional message" >> log.txt

Conclusion:

After reviewing the examples provided, you should now have a good understanding of scripting syntax, formatting, and some advanced concepts. If you're interested in diving deeper into advanced scripting and its real-world applications, consider exploring the following blogs:

https://hashnode.surajshetty.blog/real-life-applications-of-bash-scripting-explained

Thanks for reading this blog.

Did you find this article valuable?

Support Suraj Shetty by becoming a sponsor. Any amount is appreciated!

ย