Govur University Logo
--> --> --> -->
...

Demonstrate how to declare and use variables in a shell script.



In shell scripting, variables are used to store and manipulate data. They allow you to store values and refer to them by a name throughout your script. Let's explore how to declare and use variables in a shell script, specifically using the Bash shell.

1. Variable Declaration:
* To declare a variable, you simply assign a value to it using the assignment operator (`=`). No spaces are allowed around the equals sign.
* Variable names in shell scripting are case-sensitive and can consist of letters, digits, and underscores. However, they should start with a letter or an underscore.
* Here's an example of declaring variables in a shell script:

```
bash`#!/bin/bash

# Declare a variable with a string value
name="John Doe"

# Declare a variable with a numeric value
age=30

# Declare a variable with a command substitution
current_date=$(date +%Y-%m-%d)`
```
In the above example, we declared three variables: `name` with a string value, `age` with a numeric value, and `current_date` with the result of the `date` command.

2. Variable Usage:
* To access the value stored in a variable, you can use the variable's name by prefixing it with a dollar sign (`$`).
* Here's an example of using variables in a shell script:

```
bash`#!/bin/bash

# Declare variables
name="John Doe"
age=30

# Display the values of variables
echo "Name: $name"
echo "Age: $age"

# Concatenate variables with strings
greeting="Hello, $name! You are $age years old."
echo $greeting`
```
In the above example, we use the variables `name` and `age` to display their values using the `echo` command. The variables are referenced by prefixing them with a dollar sign (`$`).

We can also concatenate variables with strings by simply placing them adjacent to each other within the `echo` statement, as shown in the `greeting` example.

3. Reassigning Variables:
* Variables can be reassigned with new values throughout the script.
* To update the value of a variable, simply assign a new value to it using the assignment operator (`=`).
* Here's an example of reassigning a variable:

```
bash`#!/bin/bash

# Declare and display a variable
message="Hello, World!"
echo $message

# Reassign the variable
message="Goodbye, World!"
echo $message`
```
In the above example, we initially assign the value "Hello, World!" to the `message` variable and display it. Later, we reassign the `message` variable with a new value "Goodbye, World!" and display it again.

By declaring and using variables in a shell script, you can store and manipulate data, make your script dynamic and customizable, and enhance its functionality. Variables provide a way to hold and reference information, allowing you to perform operations based on the stored values and create more flexible and powerful shell scripts.

Log in to view the answer



Redundant Elements