Shell Scripting Basics

Table of Contents

Shell Scripting Basics

Introduce learners to the fundamentals of shell scripting, empowering them to automate tasks and create straightforward scripts in a Linux environment.

Shell Scripting Commands

  • The following simple command prints “Hello, World!” to the terminal. It illustrates the basic structure of a shell script command.

echo "Hello, World!"

  • The following shebang line specifies the shell to be used. In this case, #!/bin/bash indicates the Bash shell. It’s essential for script execution.

#!/bin/bash

  • These following commands showcase variable usage. The first line assigns a value to a variable, and the second line echoes its value to the terminal.

variable="Hello"

echo $variable

  • Make the script executable with chmod +x and execute it using ./script.sh. This is a common sequence for running shell scripts.

chmod +x script.sh

./script.sh

  • The following commands show variable assignments with different data types and the use of variables within an echo statement.

name="John"

age=25

echo "Name: $name, Age: $age"

  • The following commands use read for user input and echo for output. The script prompts the user for their name and then greets them.

echo "Enter your name:"

read username

echo "Hello, $username!"

  • The following script uses an if statement to check if a user-entered number is greater than 10 and provides a corresponding message.

read -p "Enter a number: " num

if [ $num -gt 10 ]; then

read -p "Enter a number: " num

echo "The number is greater than 10."

else

echo "The number is not greater than 10."

fi

  • The following loop iterates five times, echoing the current iteration number in each loop. It indicates a simple for loop.

for i in {1..5}; do

echo "Iteration: $i"

done

  • The following script defines a function greet that takes a parameter and echoes a greeting. It then calls the function with an argument.

greet() {

echo "Hello, $1!"

}

greet "Alice"

  • The following are commented lines at the beginning of a script. Proper comments and script headers enhance readability and maintenance.

#!/bin/bash

# Script Name: example.sh

# Author: Your Name

# Date: 2024-01-01

echo "This is a well-commented script."

By covering these shell scripting basics, learners will get basic knowledge, allowing them to automate tasks and progressively develop more complex scripts to enhance their Linux experience.

We are providing Best DevOps Courses

what you need to know

in your inbox every morning