How to use and ad variables on Bash Scrip.

How To Use And Ad Variables On Bash Scrip.

Bash scripting is a powerful tool for automating tasks in the Linux environment. One of the fundamental concepts in Bash scripting is variables. Variables allow you to store and manipulate data within a script. In this article, we will explore the basics of Bash script variables with simple examples.

  1. Variable Naming and Assignment:

  • Variables in Bash are case-sensitive and can consist of letters, numbers, and underscores.

  • To assign a value to a variable, use the “=” operator.

  • Example:

greeting
"Hello, World!"
age
25
  1. Accessing Variable Values:

  • To access the value of a variable, prefix it with the “$” symbol.

  • Example:

echo
$greeting
# Output: Hello, World!
echo
$age
# Output: 25
  1. Command Substitution:

  • Bash allows you to assign the output of a command to a variable using command substitution.

  • Example:

date
"Today's date is $current_date"
  1. Read-Only Variables:

  • You can make a variable read-only using the “readonly” command.

  • Example:

readonly
"John"
"Mike"
# This will produce an error
  1. Environment Variables:

  • Environment variables are predefined variables that are available to all Bash scripts.

  • Examples:

/home/u
/usr/
/sbin:/u
/local/
/usr/
/usr/
/sbin:/
  1. Arithmetic Operations:

  • Bash supports basic arithmetic operations using the “$(( ))” syntax.

  • aExmple:

num1
num2
sum
"The sum is: $sum"

Conclusion:

Understanding Bash script variables is crucial for writing effective scripts. By storing and manipulating data using variables, you can create dynamic and efficient scripts. Experiment with the examples provided to gain a better understanding of how variables work in Bash scripting. Happy scripting!