Bash – ExpLinux https://www.explinux.com Explore Linux How to, Tutorials, Unix, Updates, Technology. Tue, 01 Aug 2023 20:45:21 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.3 https://www.explinux.com/wp-content/uploads/2023/04/cropped-favicon-32x32-1-32x32.png Bash – ExpLinux https://www.explinux.com 32 32 Variables in Bash Scripting: A Beginner’s Guide https://www.explinux.com/2023/08/variables-in-bash-scripting.html https://www.explinux.com/2023/08/variables-in-bash-scripting.html#respond Tue, 01 Aug 2023 20:45:17 +0000 https://www.explinux.com/?p=895 Variables in Bash Scripting: A Beginner’s Guide Read More »

]]>
Variables in Bash Scripting: A Beginner’s Guide
Variables in Bash Scripting A Beginners Guide Variables in Bash Scripting
Variables in Bash Scripting: A Beginner’s Guide

As a newbie to the world of Linux and scripting, understanding the concept of variables in Bash scripting can be both essential and intriguing. Variables play a fundamental role in storing and manipulating data within a script, allowing you to create dynamic and interactive scripts. Always use variables in the script to make your life easier. In this article, we’ll learn the basics of variables in Bash scripting, how to declare the variable in Bash scripting and use it, and interactive examples with commands to help you grasp the concept effectively.

If you are new to bash script read: How to write your first bash script

What are Variables in Bash Scripting?

In any programming, a variable is a symbolic name or identifier that represents a value or data stored in the computer’s or server’s memory. Variables act as containers that hold different types of information, such as numbers, text, filenames, and more. In Bash scripting, variables enable you to store values temporarily in memory and reference them throughout your script and you can use the same multiple times because Bash is dynamically typed, making it easier to work with data dynamically.

Declaring Variables in Bash

In Bash, declaring a variable is as simple as assigning a value to it with a “=” sign. There are no data types required when declaring a variable; Bash automatically determines the type based on the context. To declare a variable in bash, use the below syntax:

variable_name=value

For example, to store the value “Hello, Explinux!” in a variable called as below example :

greeting="Hello, Explinux!"

Remember that there should be no spaces around the equal sign when declaring a variable in Bash scripting. For string use “” and number you can use 1 or any number without “”.

Using Variables in Bash

Once we have declared a variable, you can use it throughout your script by referencing its name with a dollar sign ($). For example, to print the value of the greeting variable which we have declared before, you can use the echo command:

greeting="Hello, Explinux!"
echo $greeting

The output of the script will be when you run it :

Hello Explinux!

Using the dollar sign ($) before the variable name in the script tells Bash to substitute the variable with its value during execution.

Commands with Variables

Variables in Bash are not limited to static values; they can also hold the output of commands and that is useful to write automation scripts. By enclosing the Linux command in backticks (`) or using the $() syntax, you can capture the command’s output and store it in a variable.

Example: Command Output in a Variable

#!/bin/bash
# Command Output in a Variable

# Store the current date in a variable using backticks
current_date=`date`

# Print the value of the variable
echo "Current Date: $current_date"

In this above example, the date command retrieves the current date, and we store the output in the current_date variable. The echo command then displays the value of the current_date variable in the terminal, showing the current date when the script is run.

Example: Command Output in a Variable with $()

#!/bin/bash
# Command Output using $() in a Variable.

# Store the output of the 'ls' command in a variable using $()
files=$(ls)

# Print the value of the variable
echo "Files in the current directory: $files"

Here, the ls command lists the files in the current directory where the script is executed. We use the $() syntax to capture the output of the ls command and store it in the files variable. The echo command then displays the stored value of the files variable, after execution, it will show the list of files in the directory.

Rules for Naming Variables

When naming variables in Bash scripting, you need to follow certain rules to define variables:

  1. Variable names must begin with an alphabetic letter (a-z or A-Z) or an underscore (_).
  2. After the first character, variable names can also include digits (0-9).
  3. No spaces are allowed in variable names in the bash script.
  4. Variable names are case-sensitive. For example, greeting and Greeting are considered two different variables. This is due to Linux also case sensitive.

Arithmetic with Variables

Performing arithmetic operations in Bash scripting is a good example to learn variables. Let’s see an example of how to use variables for arithmetic:

#!/bin/bash
# Arithmetic with Variables

# Declare two variables
num1=10
num2=5

# Perform arithmetic operations
sum=$((num1 + num2))
difference=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))

# Print the results
echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Quotient: $quotient"

In this example, we declare two variables num1 and num2 and perform various arithmetic operations (addition, subtraction, multiplication, and division) using these two variables. The output will be using the echo command, demonstrating how variables can store and manipulate data in Bash script.

Accepting User Input as Variable

Variables are also useful for accepting user input and processing or manipulating it in the script. Let’s see below a simple script example that takes the user’s name as input and greets them:

#!/bin/bash
# Accept User Input and Greet

# Ask the user for their name
read -p "Enter your name: " name

# Greet the user with variable name($name)
echo "Hello, $name! Nice to meet you."

In this script, we use the read command to prompt the user for their name and store the input in the name variable. The entered name by the user is then used in the greeting message when the script is executed. This is just an example you can use commands as well or any other input.

Conclusion

Variables are the building blocks of Bash scripting, enabling you to store, manipulate, and interact with data dynamically. With the knowledge of how to declare and use variables, you can create more flexible and powerful Bash scripts. Remember the basic syntax for declaring variables, use the dollar sign ($) to reference their values, and follow the rules for naming variables.

As you continue your journey into the world of Bash scripting, the understanding of variables will become more crucial as you explore advanced concepts like loops, conditionals, and functions. Practice creating scripts that utilize variables in various scenarios, and you’ll soon gain confidence in your ability to develop efficient and functional Bash scripts to automate tasks and enhance your productivity. Happy scripting

]]>
https://www.explinux.com/2023/08/variables-in-bash-scripting.html/feed 0
How to Write and Run First Bash Script https://www.explinux.com/2023/08/how-to-write-first-bash-script.html https://www.explinux.com/2023/08/how-to-write-first-bash-script.html#respond Mon, 31 Jul 2023 20:52:28 +0000 https://www.explinux.com/?p=879 How to Write and Run First Bash Script Read More »

]]>
How to Write and Run First Bash Script
How to Write and Run First Bash Script

If you’re new to the world of Linux Administration and scripting, writing your first Bash script might seem intimidating. However, fear not! Bash scripting is a very beginner-friendly way to automate tasks and interact with the command-line interface, it is the first step to automation. In this article, we’ll guide you through the process of writing and running your very first Bash script.

Read More : Introduction to Bash scripting

Getting Started

To begin, open a text editor on your system. You can use your favorite plain text editor like vi or nano.

If you do not know VI editor read: How to use vi editor

Write the First Bash Script

In the text editor, type the following lines to create your Hello World Bash script:

If you are using vi editor give the name with .sh extension. Like below example

  • # vi hello_world.sh

#!/bin/bash
# This is a simple Hello World Bash script
echo "Hello, World!"

Let’s understand the code :

#!/bin/bash: The first line is called the “shebang,” which tells the system to use the Bash interpreter to run the script. It ensures that the bash script is executed using the correct shell. Sometimes it can be changed if you are using a customized system otherwise it will be the same for all Linux systems.

# This is a simple Hello World Bash script: This line is a comment. Comments start with the # symbol and are ignored by the Bash interpreter. They provide useful information to user or if you share the script with some other guy this will tell about the script’s purpose and help understand the code.

echo "Hello, World!": The command echo in Linux Bash is used to display messages on the terminal or shell. Our script will print “Hello, World!” when the script is executed. In this place, you can use any command like ls, df -h, or any it will run.

Save the Script

After writing the script, save the bash script with a meaningful name and the .sh extension. For example, you can save it as hello_world.sh in our case. If you are using vi or nano then we may have already given it a meaningful name and saved it with press the esc button and writing “:wq!” press enter key.

Make the Script Executable

Before running our bash script, we need to make it executable. Open your terminal or command prompt and navigate to the directory where you saved the script or you have to provide the path as well with the script. Then, use the following chmod command to give execute permissions to the script:

# chmod +x hello_world.sh

The chmod command changes file permissions, you can use the man command to check more usages and +x makes the script executable for the current user.

Run the Script

From the above action, your script is now executable, it’s time to run it! In the terminal or command prompt shell, enter the below command:

./hello_world.sh

or

sh hello_world.sh

The ./ before the script name specifies the current directory and default shell, and then the script name is provided. sh is also to tell the script is a shell script and runs from the default shell. Press Enter to run script , and you should see the output:

Hello, World!

Congratulations! You have successfully written and run your first Hello World Bash script journey. Now you are one step ahead.

Troubleshooting

If you encounter any issues running the bash script, follow the below steps to troubleshooting :

  • The shebang (#!/bin/bash) is the first line of the bash script.
  • The bash script file should have the .sh extension.
  • The script has to execute permissions (use chmod +x) or use chmod u+x script name.
  • You are running the script from the correct directory (use ./ before the script name). If not give a full path like ./home/username/hello_world.sh.

Conclusion

Writing and running your first Hello World Bash script is an exciting milestone in your journey as a Linux automation programmer. With this basic foundation, you can continue exploring Bash scripting and its many possibilities to automate tasks and reduce manual errors. As you gain more experience with time, you’ll find yourself creating powerful scripts to automate tasks and streamline your workflow. So keep practicing, experiment with different commands in place of echo, and embrace the world of Bash scripting! Happy scripting!

]]>
https://www.explinux.com/2023/08/how-to-write-first-bash-script.html/feed 0
Introduction to Bash Scripting – An Essential Part of Administration https://www.explinux.com/2023/08/introduction-to-bash-scripting.html https://www.explinux.com/2023/08/introduction-to-bash-scripting.html#respond Mon, 31 Jul 2023 19:33:37 +0000 https://www.explinux.com/?p=868 Introduction to Bash Scripting – An Essential Part of Administration Read More »

]]>
Introduction to Bash Scripting
Introduction to Bash Scripting Variables in Bash Scripting

Bash scripting is a powerful tool for system administrators that allows users to automate repetitive tasks, automate workflows, and perform complex operations in a command-line environment. If you’ve never worked with bash scripting before, it might seem daunting at first, but if you are familiar with Linux basics then with a little guidance, you can quickly grasp the fundamentals and start harnessing the full potential of the Bash shell scripting. Let’s start your journey of Bash scripting.

If you interested in Linux Directory Structure

What is Bash Scripting?

Bash, short for “Bourne Again Shell,” is a Unix shell and cli language that provides an interface for users to interact with the Linux operating system. Bash scripting involves writing a series of Linux commands, often referred to as a script, to be executed by the Bash shell. These scripts are essentially small programs that can automate tasks or perform various operations on the system- to reduce task time and manual errors. If you are using a Linux Operating system it is already prebuilt and no third-party installation or setting is required. If you are able to run the command you will able to use bash script.

For example, let’s start with  “Hello, World!” to the terminal:

#!/bin/bash
# This is a simple Bash script
echo "Hello, World!"

Save the above code in a file named hello_world.sh and make this script executable with chmod +x hello_world.sh. Then, run the script using ./hello_world.sh or sh hello_world.sh. The output “Hello, World!” will be displayed on the terminal.

Getting Started with Bash Variables

Variables in any script are used to store data that can be later manipulated or referenced in the script. They are for holding information that changes throughout the script’s execution. Likely a dynamic script it can be defined before use

Below example of using variables to greet a user:

#!/bin/bash
# Example of using variables use in bash script 
name="explinux"
echo "Hello, $name! How are you today?"

Save the above code in a file named greeting.sh and make this script executable with chmod +x greeting.sh. Then, run the script using ./greeting.sh or sh greeting.sh. The output “Hello, explinux! How are you today?” will be displayed on the terminal. Where $name is replaced with the value we have stored in the variable.

Conditional Statements in Bash

Conditional statements allow you to make decisions in our automation script based on given certain conditions like other programming languages. The most commonly used conditional for any script statement in Bash is the if statement which is similar to any other programming language. Only the written part is different we need to tell where the condition ends.

Let’s create a script that checks if a number is positive or negative with the bash script :

#!/bin/bash
# Example of using conditional statements
read -p "Enter a number: " num

if [ $num -gt 0 ]; then
    echo "The number is positive."
elif [ $num -lt 0 ]; then
    echo "The number is negative."
else
    echo "The number is zero."
fi

Save the above code in a file named positive_negative_check.sh, make it executable, and then run the script as we did in the above examples. Enter a number, and the script will display whether the number is positive, negative, or zero.

Looping in Bash

Loops are used to repeat a set of commands or functions multiple times. In Bash, we have for and while loops to achieve this loop condition.

For example, let’s create a script that prints numbers from 1 to 5 using a for loop:

#!/bin/bash
# Example of using a for loop
for i in {1..5}; do
    echo "Number: $i"
done

Save the above code and name it number_loop.sh, make it executable with chmod -x number_loop.sh , and then run the script sh number_loop.sh or ./number_loop.sh. We will see the output with numbers from 1 to 5 printed on the terminal.

Conclusion

Bash scripting is a valuable skill for every Linux admin or Linux automation engineer. With just learning the basics of Bash scripting, we can enhance our productivity, automate tasks, and simplify complex operations on our systems. We covered the essential concepts of Bash scripting, including creating scripts, using variables, implementing conditional statements, and employing loops. With this foundation, you can start playing with Bash scripting. We have a full list or articles on bash scripting check those out to learn more. So, start scripting, and enjoy the power of automation!

]]>
https://www.explinux.com/2023/08/introduction-to-bash-scripting.html/feed 0