5 Shell Scripts for Linux Newbies to Learn Shell Programming


If you're new to Linux, learning shell scripting can seem daunting at first. However, shell scripting can be an incredibly useful skill to have when working with Linux systems. Shell scripts can automate repetitive tasks, perform system administration tasks, and even help with software development.

In this article, we'll look at five shell scripts that Linux newbies can learn to get started with shell programming. We'll cover some basics of shell scripting, and provide examples of each script to help you understand how they work.

What is Shell Scripting?

A shell script is a program written in a scripting language that runs in a Unix/Linux shell. Shell scripting is a powerful tool that allows you to automate tasks, perform system administration tasks, and even create software.

Shell scripts are executed in a command-line interface, and they can be used to perform a wide variety of tasks, from basic file management to complex data processing.

Script 1: Hello World

The first script that every programmer learns is classic "Hello, World!" program. It's a simple script that just prints a message to screen. Here's what script looks like −

Example

#!/bin/bash
echo "Hello, World!"

Output

Hello, World!

Let's break this down. first line of script is called "shebang" line, and it tells shell which interpreter to use to run script. In this case, we're using bash shell.

The second line is actual command that prints message to screen. echo command simply displays text that follows it.

To run script, save it to a file (e.g., hello.sh), make it executable with chmod +x hello.sh command, and then run it with ./hello.sh.

Script 2: Simple Calculator

The next script we'll look at is a simple calculator. This script takes two numbers as input from user and performs a basic arithmetic operation on them. Here's what script looks like −

Example

#!/bin/bash
echo "Enter first number: "
read num1
echo "Enter second number: "
read num2
echo "The sum is: $((num1 + num2))"

Output

Enter first number: 
Enter second number: 
The sum is: 0

Let's break this down. first two lines of script prompt user to enter two numbers, and then read those numbers into num1 and num2 variables.

The third line performs actual calculation. In this case, we're adding num1 and num2 together using $(( )) syntax.

To run script, save it to a file (e.g., calculator.sh), make it executable with chmod +x calculator.sh command, and then run it with ./calculator.sh.

Script 3: File Backup

The next script we'll look at is a file backup script. This script copies a file to a backup directory and adds a timestamp to file name. Here's what script looks like −

#!/bin/bash
backup_dir=/path/to/backup/dir/
filename=file.txt
cp $filename $backup_dir/${filename}_$(date +%Y-%m-%d_%H-%M-%S)

Let's break this down. first line of script sets a variable called backup_dir to path of backup directory.

The second line sets a variable called filename to name of file we want to back up.

The third line copies file to backup directory using cp command. ${filename}_$(date +%Y-%m-%d_%H-%M-%S) syntax adds a timestamp to end of file name, so that each backup has a unique name.

To run script, save it to a file (e.g., backup.sh), make it executable with chmod +x backup.sh command, and then run it with ./backup.sh.

Script 4: System Information

The next script we'll look at is a system information script. This script displays information about system, such as operating system, kernel version, and CPU information. Here's what script looks like −

Example

#!/bin/bash
echo "Operating system: $(uname -o)"
echo "Kernel version: $(uname -r)"
echo "CPU information: $(lscpu | grep "Model name" | awk '{print $3, $4, $5, $6, $7, $8}')"

Output

Operating system: GNU/Linux
Kernel version: 5.15.0-60-generic
CPU information: AMD Ryzen 9 5950X 16-Core Processor

Let's break this down. first line of script is shebang line, as usual.

The next three lines use various commands to display system information. uname -o command displays operating system, uname -r command displays kernel version, and lscpu | grep "Model name" | awk '{print $3, $4, $5, $6, $7, $8}' command displays CPU information.

To run script, save it to a file (e.g., systeminfo.sh), make it executable with chmod +x systeminfo.sh command, and then run it with ./systeminfo.sh.

Script 5: Password Generator

The last script we'll look at is a password generator. This script generates a random password using a combination of uppercase and lowercase letters, numbers, and special characters. Here's what script looks like −

Example

#!/bin/bash
length=12
password=$(cat /dev/urandom | tr -dc 'a-zA-Z0-9!@#$%^&*()_+-=' | fold -w $length | head -n 1)
echo "Your new password is: $password"

Output

Your new password is: YRY+zm:<JwYi

Let's break this down. first line of script is shebang line, as usual.

The second line sets a variable called length to desired length of password.

The third line generates a random password using cat /dev/urandom | tr -dc 'a-zA-Z0-9!@#$%^&*()_+-=' | fold -w $length | head -n 1 command. This command uses cat /dev/urandom command to generate random data, and then uses tr command to filter out unwanted characters. fold -w $length command breaks output into lines of desired length, and head -n 1 command selects first line (i.e., password).

To run script, save it to a file (e.g., password.sh), make it executable with chmod +x password.sh command, and then run it with ./password.sh.

Scritp 6: File Search

A script that allows you to search for files in a directory or subdirectories based on a keyword. Here's an example −

#!/bin/bash
echo "Enter directory to search: "
read dir
echo "Enter keyword to search for: "
read keyword
find $dir -name "*$keyword*" -print

This script prompts user to enter a directory and a keyword to search for, and then uses find command to search for files with that keyword in their names.

Script 7: Directory Backup

A script that backs up an entire directory (including subdirectories and files) to a backup location. Here's an example −

#!/bin/bash
src_dir=/path/to/src/dir/
backup_dir=/path/to/backup/dir/
tar -czf $backup_dir/backup_$(date +%Y-%m-%d_%H-%M-%S).tar.gz $src_dir

This script sets variables for source directory and backup directory, and then uses tar command to create a compressed archive of source directory in backup directory, with a timestamp in filename.

Script 8: Process Monitoring

A script that monitors a specific process and sends an alert if process stops running. Here's an example −

#!/bin/bash
process_name=myprocess
while true
do
   if ps aux | grep $process_name | grep -v grep > /dev/null
   then
      sleep 1
   else
      echo "$process_name has stopped running."
      mail -s "Process Monitor Alert" user@example.com <<< "$process_name has stopped running."
      break
   fi
done

This script uses a while loop to continuously check if a process with a specific name is running using ps command. If process is not running, script sends an email alert to specified user using mail command.

Scritp 9: Web Scraping

A script that extracts data from a website and stores it in a file or database. Here's an example using curl and grep commands −

#!/bin/bash
url="http://example.com"
data=$(curl -s $url)
echo $data | grep -oP '(?<=).*?(?=)' > title.txt

This script uses curl command to retrieve HTML content of a webpage, and then uses grep to extract title tag and save it to a file.

Script 10: SSH Automation

A script that automates SSH login and command execution on remote servers. Here's an example using sshpass command −

#!/bin/bash
server="example.com"
username="user"
password="password"
command="ls"
sshpass -p $password ssh $username@$server $command

This script uses sshpass command to automate SSH login and execute a command on a remote server without user interaction.

Script 11: Database Backup

A script that performs backups of a MySQL database and uploads them to a remote server. Here's an example using mysqldump command and rsync command −

#!/bin/bash
db_name="mydb"
db_user="user"
db_password="password"
backup_dir="/path/to/backup/dir/"
backup_file="$backup_dir/backup_$(date +%Y-%m-%d_%H-%M-%S).sql"
mysqldump -u $db_user -p$db_password $db_name > $backup_file
rsync -avz $backup_dir user@example.com:/path/to/remote/dir/

This script uses mysqldump command to perform a backup of a MySQL database and save it to a file with a timestamp in name. It then uses rsync command to upload backup file to a remote server.

Conclusion

Shell scripting is a powerful tool that can help you automate tasks, perform system administration tasks, and even create software. scripts we covered in this article are just tip of iceberg when it comes to shell scripting, but they should give you a good foundation to start building your own scripts.

Remember, practice makes perfect, so don't be afraid to experiment with different commands and scripts to see what works best for you. Happy scripting!

Updated on: 11-Apr-2023

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements