| by Arround The Web

How to Install Fail2ban on Ubuntu 24.04 Server

Fail2ban is free and open-source IPS (Intrusion Prevention Software) that helps administrators secure Linux servers against malicious login and brute-force attacks. In this guide, you’ll learn how to install Fail2ba on Ubuntu 24.04 server.
The po…

Share Button
Read More
| by Arround The Web

Linux Bash Scripting Part 2: Functions, Arguments, and Basic Error Handling

In Part 1 of this tutorial series, we introduced the basics of Bash scripting on Linux. We learned how to write simple scripts, use variables, loops, conditionals, and even schedule tasks with cron. Now, let’s build on that knowledge with some beginner-friendly, yet more advanced, techniques.

In this article, we’ll explore:

  • Functions: Reusable blocks of code to keep your scripts clean and organized.
  • Command-line arguments: How to make your scripts accept input directly from the terminal.
  • Basic error handling: Checking for problems so your scripts can deal with them gracefully.
  • Simple logging: How to capture the output of your script for future reference.

Don’t worry, we’ll keep things simple and explain everything along the way. By the end of this guide, you’ll feel more confident about writing Bash scripts that are a little more dynamic and smarter!


1. Using Functions to Keep Things Organized

As your scripts get bigger, you’ll notice you’re doing similar things in different parts of the script. That’s where functions come in handy. A function is a way to group commands together and reuse them throughout your script.

Think of it like a recipe you can call anytime you need it!

How to Create a Function

The syntax for creating a function is simple:

Bash:

function_name() {
# Your commands here
}

Let’s say you want to greet the user. Instead of writing the same command over and over again, you can create a function for it:

Bash:

#!/bin/bash
# Define a function to greet the user
greet_user() {
echo “Hello, $1! Welcome to Bash scripting!”
}

# Call the function
greet_user “Alice”
greet_user “Bob”

In this script:

  • We define the function greet_user that prints a greeting.
  • $1 represents the first argument passed to the function (in this case, the user’s name).

When you run the script, you’ll see:

Hello, Alice! Welcome to Bash scripting!
Hello, Bob! Welcome to Bash scripting!

You can pass different names to the function, making it reusable. Functions are super helpful when you need to use the same logic multiple times in your script.


2. Command-Line Arguments: Making Your Script Interactive

Wouldn’t it be great if you could pass information to your script when you run it, instead of hardcoding values into it? Bash lets you do that with command-line arguments.

What Are Command-Line Arguments?

Command-line arguments allow you to pass data to your script from the terminal. For example, instead of telling the script what to do beforehand, you give it instructions when you run it.

Here’s an example script that accepts a name and a favorite color as arguments:

Bash:

#!/bin/bash
# The first argument is the name, the second is the favorite color
greet_user() {
name=$1
color=$2

echo “Hello, $name! Your favorite color is $color.”

Let’s say you save this script as greet.sh. You can run it from the terminal like this:

./greet.sh Alice blue

And the output will be:

Hello, Alice! Your favorite color is blue.

Accessing Command-Line Arguments

  • $1, $2, $3, etc., represent the first, second, third argument, and so on.
  • $0 represents the script’s name.
  • $# gives the total number of arguments passed.

This makes your scripts much more flexible. Now, instead of changing the script every time you want to run it with different inputs, you just pass new arguments directly from the terminal!


3. Basic Error Handling: Dealing with Problems

Not everything goes smoothly in scripting, especially when dealing with files or commands that might fail. That’s why it’s important to include error handling in your script. You don’t want your script to keep running if something goes wrong!

Checking the Exit Status of a Command

Every command in Bash returns an exit status:

  • 0 means the command was successful.
  • Any number other than 0 means something went wrong.

We can use this exit status to handle errors. For example, let’s check if a file exists before trying to copy it:

bash:

#!/bin/bash

# Check if the file exists before copying
if [ -f “$1” ]; then
cp “$1” /backup/
echo “File copied successfully.”
else
echo “Error: $1 does not exist.”
exit 1 # Exit with an error code
fi

Here’s how this script works:

  1. The if [ -f "$1" ] checks if the file exists (-f checks for a file).
  2. If the file exists, it copies the file.
  3. If the file doesn’t exist, it prints an error message and exits the script with an error code (1).

If you run the script like this:

./copy.sh myfile.txt

And myfile.txt doesn’t exist, you’ll see:

Error: myfile.txt does not exist.

Adding error handling like this helps your script avoid continuing with bad data or broken commands.


4. Simple Logging: Keeping Track of What Happens

Logging is a way to record what your script does. Instead of relying on memory or watching the terminal, you can save everything that happens into a file for future reference.

Redirecting Output to a Log File

You can easily redirect the output of your script to a file. Here’s how:

Bash:

#!/bin/bash
# Redirect output to a log file
exec > script.log 2>&1

echo “This is a log of everything that happens in this script.”
date # Logs the current date and time
echo “Done!”

Let’s break it down:

  • exec > script.log 2>&1 redirects all output (both standard output and error messages) to a file called script.log.
  • Now, anything the script prints will go to the log file instead of the terminal.

After running the script, open script.log, and you’ll see:

This is a log of everything that happens in this script.
Tue Oct 17 10:00:00 UTC 2024
Done!

Logging is incredibly useful for tracking what happens in long-running or automated scripts.


5. Combining It All: A Simple Example

Now, let’s combine everything we’ve learned so far into one simple script. This script will:

  1. Accept a filename as an argument.
  2. Check if the file exists.
  3. If it exists, copy it to a backup directory and log the action.
  4. If it doesn’t exist, log an error.

Here’s the script:

bash:

#!/bin/bash

# Redirect all output to a log file
exec > backup.log 2>&1

# Check if exactly one argument (a file name) is passed
if [ $# -ne 1 ]; then
echo “Usage: $0 filename”
exit 1
fi

# Check if the file exists
if [ -f “$1” ]; then
# Copy the file to the backup directory
cp “$1” /backup/
echo “$(date): $1 copied to /backup/”
else
echo “$(date): Error – $1 does not exist.”
exit 1
fi

If you run this script and provide a valid file, it will copy the file to /backup/ and log the success message. If the file doesn’t exist, it will log an error.


Conclusion

In this article, we’ve built on the basics of Bash scripting by introducing functions, command-line arguments, error handling, and logging. These are essential skills that will help you write more effective and robust scripts.

As you practice these new techniques, you’ll see how much more dynamic and powerful your scripts can become. Whether you’re automating backups, processing files, or just learning to make the most out of the Linux command line, you now have some new tools to get the job done!

In the next article, we’ll dive deeper into more intermediate scripting techniques, but for now, keep practicing with what you’ve learned here. Happy coding!

Share Button
Read More
| by Arround The Web

13 Best Free and Open Source Command-Line Python Application Development Tools

Python comes with several different libraries that allow you to write a command line interface for your scripts. Here are 13 of the best application development tools.
The post 13 Best Free and Open Source Command-Line Python Application Development To…

Share Button
Read More
| by Arround The Web

libunistring @ Savannah: GNU libunistring-1.3 released

Download from https://ftp.gnu.org/gnu/libunistring/libunistring-1.3.tar.gz

This is a stable release.

New in this release:

The data tables and algorithms have been updated to Unicode version 16.0.0.

New function uc_is_property_modifier_com…

Share Button
Read More
| by Arround The Web

Solus 4.6 “Convergence” Released, Here’s What’s New

Solus 4.6 debuts with Linux kernel 6.10, Usr-Merge, new multimedia defaults, and upgraded Mesa 24.2 for better hardware support.
The post Solus 4.6 “Convergence” Released, Here’s What’s New appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

Solus 4.6 “Convergence” Released, Here’s What’s New

Solus 4.6 debuts with Linux kernel 6.10, Usr-Merge, new multimedia defaults, and upgraded Mesa 24.2 for better hardware support.
The post Solus 4.6 “Convergence” Released, Here’s What’s New appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

Solus 4.6 “Convergence” Released, Here’s What’s New

Solus 4.6 debuts with Linux kernel 6.10, Usr-Merge, new multimedia defaults, and upgraded Mesa 24.2 for better hardware support.
The post Solus 4.6 “Convergence” Released, Here’s What’s New appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

36 Useful Apache ‘.htaccess’ Tricks for Security and Performance

The .htaccess file is a powerful configuration file used on Apache-based web servers to manage and modify settings at the directory level. By modifying .htaccess file, you can control many aspects of your website’s behavior without needing to alter server-wide settings. Below are 25 essential .htaccess tricks and tips that can help improve your site’s […]

The post 36 Useful Apache ‘.htaccess’ Tricks for Security and Performance appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

36 Useful Apache ‘.htaccess’ Tricks for Security and Performance

The .htaccess file is a powerful configuration file used on Apache-based web servers to manage and modify settings at the directory level. By modifying .htaccess file, you can control many aspects of your website’s behavior without needing to alter server-wide settings. Below are 25 essential .htaccess tricks and tips that can help improve your site’s […]

The post 36 Useful Apache ‘.htaccess’ Tricks for Security and Performance appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

Fwupd 2.0.1 Enhances GNOME Firmware Emulation with New API

Fwupd 2.0.1 adds API for gnome-firmware device emulation, shifts emulation-tag devices to the database, and fixes compilation issues.
The post Fwupd 2.0.1 Enhances GNOME Firmware Emulation with New API appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

Inkscape: A Powerful Free Alternative to Adobe Illustrator

Inkscape is a popular free and open-source vector graphics editor, used by artists, designers, and anyone who wants to create high-quality illustrations, icons, logos, and other types of graphics. Unlike raster images that use pixels (like in Photoshop), vector graphics are based on mathematical equations, allowing you to scale your artwork up or down without […]

The post Inkscape: A Powerful Free Alternative to Adobe Illustrator appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

How to Add and Remove Passwords from PDF Files on Linux

Find out the CLI and GUI methods to add and remove passwords from PDF files on Linux, Windows, and macOS with a practical example.
The post How to Add and Remove Passwords from PDF Files on Linux appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

The 4 best Linux desktops based on GNOME – and what I most like about each one

GNOME has inspired some great desktop environments. These are the best.

Share Button
Read More
| by Arround The Web

How to Install and Use iTunes on Ubuntu (A Quick Guide)

Learn how to install iTunes on Ubuntu using a Wine program, then how to launch iTunes on Ubuntu, including its removal steps.
The post How to Install and Use iTunes on Ubuntu (A Quick Guide) appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

Active Cooling vs Passive Cooling: What’s the difference?

When you are setting up your homelab, you’ll come across the terms active and passive cooling. Learn about the difference between the two.

Share Button
Read More
| by Arround The Web

OpenSSH Splits Again: New Authentication Binary Unveiled

The sshd splitting progresses with sshd-auth, isolating authentication in a separate binary, and reducing pre-auth attack surface in OpenSSH.
The post OpenSSH Splits Again: New Authentication Binary Unveiled appeared first on Linux Today.

Share Button
Read More
| by Arround The Web

Getting Started with Bash Scripting: A Beginner’s Guide to Automating Tasks on Linux

Linux is a powerful operating system, not only because of its stability and open-source nature but also because of the incredible control it gives users over their system. One of the most effective ways to harness this power is through Bash scripting, which allows you to automate tasks, simplify processes, and unlock greater efficiency in managing Linux environments.

In this tutorial, we’ll walk you through the basics of creating and running a Bash script. Whether you’re new to Linux or looking to expand your skills, this guide will get you started with scripting.

What is Bash?

Bash (short for Bourne Again Shell) is a command-line interpreter that provides a user interface for Unix-based systems, including Linux. The shell is where you can type commands, run programs, and interact with the underlying OS. Bash scripts are text files that contain a series of commands executed line by line.

By learning how to write Bash scripts, you can automate repetitive tasks, schedule jobs, and even build complex workflows.


Part 1: Writing Your First Bash Script

Step 1: Create a New Script File

To create a new Bash script, you first need to create a file that will store your commands. Open a terminal and use a text editor (like nano or vim) to create a new file. For this example, let’s use nano:

Bash:

nano myscript.sh

The .sh extension is commonly used for Bash scripts, though it’s not required. You can name the file anything you want.

Step 2: Add a Shebang

At the very top of your script file, include a shebang line. This tells the system that the script should be executed using Bash. The shebang is written as follows:

Bash:

#!/bin/bash

Without this line, your script might not know which shell to use, especially if you’re running it in a different environment.

Step 3: Add Commands to the Script

Now, let’s add some simple commands. For example, we can create a script that outputs “Hello, World!” and shows the current date:

Bash:

#!/bin/bash
# This is a comment
echo “Hello, World!”
echo “Today is: $(date)”

  • The echo command prints text to the terminal.
  • The $(date) command executes the `date` command and substitutes its output.

Step 4: Save and Exit

Once you’ve written your script, save the file by pressing CTRL + O in nano, then press Enter. To exit, press CTRL + X.


Part 2: Running Your Script

Step 1: Make the Script Executable

Before running your script, you need to give it executable permissions. You can do this using the chmod command:

Bash:

chmod +x myscript.sh

This command tells Linux that the file can be executed like a program.

Step 2: Run the Script

Now that your script is executable, you can run it by typing:

Bash:

./myscript.sh

You should see output similar to:

Bash:

“Hello, World!”
“Today is: Mon Oct 16 12:34:56 UTC 2024”

Congratulations! You’ve just written and executed your first Bash script.


Part 3: Adding Variables and Logic

Bash scripts become more useful when you introduce variables and basic logic. Let’s expand our script.

Step 1: Using Variables

You can store values in variables and use them throughout your script. Here’s an example of a script that asks for your name and greets you:

Bash:

#!/bin/bash
# Prompt the user for their name
echo “Enter your name:”
read name

# Greet the user
echo “Hello, $name! Welcome to Bash scripting.”

In this script:

  • The read command captures user input and stores it in the name variable.
  • Variables in Bash are referenced by prefixing the variable name with a dollar sign ($).

Step 2: Using Conditional Statements

Bash supports if statements for basic decision-making. Here’s an example that checks if the user is root (the system administrator):

Bash:

#!/bin/bash
# Check if the user is root
if [ “$USER” == “root” ]; then
echo “Hello, root user!”
else
echo “You are not the root user.”
fi

The if statement checks if the USER environment variable is equal to root. The then block runs if the condition is true, and the else block runs if it’s false.

Step 3: Loops in Bash

Bash also supports loops, which are essential when you want to repeat a task multiple times. For example, here’s a script that prints numbers from 1 to 5:

Bash:

#!/bin/bash
# Loop from 1 to 5
for i in {1..5}; do
echo “Number: $i”
done


Part 4: Making Your Script More Useful

Let’s apply what we’ve learned to automate a real task—backing up a directory. This script will copy all files from a source directory to a backup location.

Step 1: Backup Script Example

Bash:

#!/bin/bash
# Define variables
source_dir=“/home/user/documents”
backup_dir=“/home/user/backup”

# Create the backup directory if it doesn’t exist
mkdir -p “$backup_dir”

# Copy files
cp -r “$source_dir”/* “$backup_dir”

# Print a success message
echo “Backup completed successfully.”

Step 2: Scheduling with Cron

To automate running this script daily, you can use cron, a task scheduler in Linux. To set this up, follow these steps:

  • Open the cron configuration file with the following command:
Bash:

crontab -e

  • Add a new line to run your script every day at 2 AM:
Bash:

0 2 * * * /path/to/myscript.sh

Save and exit. Now, your script will run automatically every day.


Conclusion

Bash scripting is a powerful tool that allows you to automate tasks, create workflows, and manage your Linux environment more efficiently. In this tutorial, we’ve covered the basics of writing and running Bash scripts, introduced variables, logic, and loops, and demonstrated how to automate tasks with cron.

With these fundamentals, you can now explore more advanced features like functions, error handling, and interacting with other Linux tools. Happy scripting!

Share Button
Read More
| by Arround The Web

How to Run Own Online SMS Portal with playSMS in Linux

The post How to Run Own Online SMS Portal with playSMS in Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides .playSMS is an open-source SMS management software that allows you to send and receive SMS messages using various gateways and
T…

Share Button
Read More
| by Arround The Web

How to Run Own Online SMS Portal with playSMS in Linux

The post How to Run Own Online SMS Portal with playSMS in Linux first appeared on Tecmint: Linux Howtos, Tutorials & Guides .playSMS is an open-source SMS management software that allows you to send and receive SMS messages using various gateways and
T…

Share Button
Read More
| by Arround The Web

CentOS Stream: The Perfect Distribution for Development Projects

The post CentOS Stream: The Perfect Distribution for Development Projects first appeared on Tecmint: Linux Howtos, Tutorials & Guides .CentOS Stream has become a key part of the Red Hat ecosystem, offering developers an exciting opportunity to shape th…

Share Button
Read More