How to define and use variables in Bash scripts?

To define and use variables in Bash scripts, follow these steps:

  1. Variable Naming: Choose a name for your variable starting with a letter or underscore (_) followed by any combination of letters, digits, or underscores. Variable names are case-sensitive.

  2. Variable Assignment: Use the following syntax to assign a value to a variable:

    variable_name=value

    Avoid using spaces around the equals sign (=).

  3. Using Variables: To use the value stored in a variable, precede the variable name with a dollar sign ($). For example, if you have a variable named "name", you can use it like this:

    echo $name
  4. Accessing Variables Within Strings: To include the value of a variable within a string, use double quotes ("") instead of single quotes (''). For example:

    message="Hello, $name" echo $message

    The output will be "Hello, [value of name variable]”.

  5. Special Variables: Bash provides a set of predefined variables that store information like script name, command-line arguments, etc. Some commonly used special variables are:

    • $0: The name of the script.
    • $1, $2, $3, ...: The first, second, third, etc. command-line arguments.
    • $@: All the command-line arguments.
    • $#: The total number of command-line arguments.
    • $? : The exit status of the last executed command.

Here's an example Bash script using variables:

#!/bin/bash name="John Doe" age=30 echo "Name: $name" echo "Age: $age" echo "Script Name: $0" echo "First Argument: $1" echo "All Arguments: $@" echo "Total Arguments: $#" echo "Exit Status: $?"

Save the script to a file (e.g., script.sh), make it executable (chmod +x script.sh), and then run it with command-line arguments:

./script.sh argument1 argument2

The script will display the values of the variables and the provided command-line arguments.