Linux Variable Declaring

LinuxLinuxBeginner
Practice Now

Introduction

In this lab, you will learn about variables in Linux shell scripting, which are essential for storing and manipulating data in your scripts. Variables allow you to store information temporarily during script execution and reuse that information throughout your code.

Understanding how to declare and use variables is a fundamental skill for writing Linux shell scripts. This knowledge will help you automate tasks, manage configurations, and create more dynamic scripts for various applications.

By the end of this lab, you will understand how to create simple variables, integer variables, and arrays in bash scripts, which are the building blocks for more advanced shell scripting techniques.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL linux(("Linux")) -.-> linux/FileandDirectoryManagementGroup(["File and Directory Management"]) linux(("Linux")) -.-> linux/TextProcessingGroup(["Text Processing"]) linux(("Linux")) -.-> linux/VersionControlandTextEditorsGroup(["Version Control and Text Editors"]) linux(("Linux")) -.-> linux/BasicSystemCommandsGroup(["Basic System Commands"]) linux(("Linux")) -.-> linux/BasicFileOperationsGroup(["Basic File Operations"]) linux/BasicSystemCommandsGroup -.-> linux/echo("Text Display") linux/BasicSystemCommandsGroup -.-> linux/declare("Variable Declaring") linux/BasicFileOperationsGroup -.-> linux/chmod("Permission Modifying") linux/FileandDirectoryManagementGroup -.-> linux/cd("Directory Changing") linux/FileandDirectoryManagementGroup -.-> linux/mkdir("Directory Creating") linux/TextProcessingGroup -.-> linux/expr("Evaluate Expressions") linux/VersionControlandTextEditorsGroup -.-> linux/nano("Simple Text Editing") subgraph Lab Skills linux/echo -.-> lab-271265{{"Linux Variable Declaring"}} linux/declare -.-> lab-271265{{"Linux Variable Declaring"}} linux/chmod -.-> lab-271265{{"Linux Variable Declaring"}} linux/cd -.-> lab-271265{{"Linux Variable Declaring"}} linux/mkdir -.-> lab-271265{{"Linux Variable Declaring"}} linux/expr -.-> lab-271265{{"Linux Variable Declaring"}} linux/nano -.-> lab-271265{{"Linux Variable Declaring"}} end

Basic Variable Declaration

In this step, you will learn how to declare and use a basic variable in a bash script. Variables in Linux shell scripts allow you to store data temporarily and reference it later in your script.

First, let's create a directory for our project and navigate to it:

mkdir -p ~/project
cd ~/project

Now, create a script called variables.sh using the nano text editor:

nano ~/project/variables.sh

Inside the editor, type the following content:

#!/bin/bash

## Declaring a basic variable
BALLOON_COLOR="red"

## Displaying the variable value
echo "The balloon color is: $BALLOON_COLOR"

In this script, we've declared a variable named BALLOON_COLOR and assigned it the value "red". The echo command then displays the value of this variable.

To save the file in nano, press Ctrl+O, then press Enter to confirm. To exit nano, press Ctrl+X.

Now, make the script executable:

chmod +x ~/project/variables.sh

This command gives the file execute permission, allowing you to run it as a program.

Finally, execute your script:

./variables.sh

You should see the following output:

The balloon color is: red

This shows that your variable has been successfully declared and its value can be accessed using the $ symbol before the variable name.

Declaring Integer Variables

In this step, you will learn how to declare and use integer variables in bash scripts. The -i flag tells bash that the variable should be treated as an integer, which can be useful for numerical operations.

Open the variables.sh script again to edit it:

nano ~/project/variables.sh

Modify the script to include an integer variable:

#!/bin/bash

## Declaring a basic string variable
BALLOON_COLOR="red"

## Declaring an integer variable
declare -i BALLOON_SIZE=10

## Displaying both variables
echo "The balloon color is: $BALLOON_COLOR"
echo "The balloon size is: $BALLOON_SIZE inches"

## Performing arithmetic with the integer variable
declare -i DOUBLE_SIZE=BALLOON_SIZE*2
echo "Double the size would be: $DOUBLE_SIZE inches"

In this updated script:

  1. We've kept our original string variable BALLOON_COLOR
  2. We've added a new integer variable BALLOON_SIZE using the declare -i syntax
  3. We've demonstrated how to perform arithmetic operations with integer variables

Save the file with Ctrl+O and Enter, then exit nano with Ctrl+X.

Now run the script again:

./variables.sh

You should see the following output:

The balloon color is: red
The balloon size is: 10 inches
Double the size would be: 20 inches

The -i declaration allows bash to recognize that the variable should be treated as an integer, making arithmetic operations possible. This is particularly useful for counters, calculations, and numeric processing in your scripts.

Working with Array Variables

In this step, you will learn how to declare and use array variables. Arrays allow you to store multiple values under a single variable name, which is useful when dealing with collections of related data.

Let's edit our script again:

nano ~/project/variables.sh

Update the script to include an array variable:

#!/bin/bash

## Declaring a basic string variable
BALLOON_COLOR="red"

## Declaring an integer variable
declare -i BALLOON_SIZE=10

## Declaring an array variable
declare -a BALLOON_COLORS=("red" "green" "blue" "purple" "yellow")

## Displaying individual variables
echo "The balloon color is: $BALLOON_COLOR"
echo "The balloon size is: $BALLOON_SIZE inches"

## Displaying all array elements
echo "Available balloon colors are: ${BALLOON_COLORS[*]}"

## Displaying specific array elements
echo "The first color is: ${BALLOON_COLORS[0]}"
echo "The third color is: ${BALLOON_COLORS[2]}"

## Count of array elements
echo "Number of available colors: ${#BALLOON_COLORS[@]}"

In this updated script:

  1. We've kept our existing variables
  2. We've added an array variable BALLOON_COLORS using the declare -a syntax
  3. We've shown different ways to access array elements:
    • ${BALLOON_COLORS[*]} displays all elements
    • ${BALLOON_COLORS[0]} accesses the first element (arrays in bash are zero-indexed)
    • ${#BALLOON_COLORS[@]} gives the number of elements in the array

Save the file with Ctrl+O and Enter, then exit nano with Ctrl+X.

Now run the script again:

./variables.sh

You should see the following output:

The balloon color is: red
The balloon size is: 10 inches
Available balloon colors are: red green blue purple yellow
The first color is: red
The third color is: blue
Number of available colors: 5

Arrays are powerful when you need to manage collections of related data. They allow you to organize multiple values and access them individually or as a group. This is especially useful for managing lists of items, such as filenames, user information, or configuration options.

Variable Manipulation and Expansion

In this step, you will learn how to manipulate and expand variables in different ways. These techniques allow you to modify variable values without creating new variables, which is useful for text processing and data transformation.

Let's edit our script again:

nano ~/project/variables.sh

Update the script to demonstrate variable manipulation:

#!/bin/bash

## Declaring basic variables
NAME="linux"
MESSAGE="Hello, world!"
FILE_PATH="/home/user/documents/report.txt"

echo "Original values:"
echo "NAME = $NAME"
echo "MESSAGE = $MESSAGE"
echo "FILE_PATH = $FILE_PATH"

echo -e "\nVariable manipulation examples:"

## Convert to uppercase
echo "NAME in uppercase: ${NAME^^}"

## Convert to lowercase
UPPER_NAME="LINUX"
echo "UPPER_NAME in lowercase: ${UPPER_NAME,,}"

## Get string length
echo "Length of MESSAGE: ${#MESSAGE}"

## Extract substring (starting at position 7, 5 characters)
echo "Substring of MESSAGE: ${MESSAGE:7:5}"

## Replace part of string
echo "Replace 'world' with 'Linux': ${MESSAGE/world/Linux}"

## Extract filename from path
echo "Filename from path: ${FILE_PATH##*/}"

## Extract directory from path
echo "Directory from path: ${FILE_PATH%/*}"

## Default value if variable is unset
UNSET_VAR=""
echo "Default value example: ${UNSET_VAR:-default value}"

This script demonstrates several methods for manipulating variables:

  1. ${NAME^^} - Convert to uppercase
  2. ${UPPER_NAME,,} - Convert to lowercase
  3. ${#MESSAGE} - Get string length
  4. ${MESSAGE:7:5} - Extract substring (position and length)
  5. ${MESSAGE/world/Linux} - Replace part of string
  6. ${FILE_PATH##*/} - Remove the longest match from the beginning (extract filename)
  7. ${FILE_PATH%/*} - Remove the shortest match from the end (extract directory)
  8. ${UNSET_VAR:-default value} - Use default if variable is unset

Save the file with Ctrl+O and Enter, then exit nano with Ctrl+X.

Now run the script:

./variables.sh

You should see output similar to:

Original values:
NAME = linux
MESSAGE = Hello, world!
FILE_PATH = /home/user/documents/report.txt

Variable manipulation examples:
NAME in uppercase: LINUX
UPPER_NAME in lowercase: linux
Length of MESSAGE: 13
Substring of MESSAGE: world
Replace 'world' with 'Linux': Hello, Linux!
Filename from path: report.txt
Directory from path: /home/user/documents
Default value example: default value

These variable manipulation techniques are extremely useful for processing text data, extracting information from strings, and handling default values in your scripts.

Environment Variables and Variable Scope

In this final step, you will learn about environment variables, variable scope, and how to export variables to make them available to other processes.

Create a new script called environment.sh:

nano ~/project/environment.sh

Add the following content:

#!/bin/bash

## Displaying some common environment variables
echo "USER: $USER"
echo "HOME: $HOME"
echo "PATH: $PATH"
echo "PWD: $PWD"
echo "SHELL: $SHELL"

## Creating a local variable
LOCAL_VAR="This is a local variable"
echo "LOCAL_VAR: $LOCAL_VAR"

## Exporting a variable to make it available to child processes
export EXPORTED_VAR="This variable is exported"
echo "EXPORTED_VAR: $EXPORTED_VAR"

## Demonstrate how variables work in subshells
echo -e "\nVariable behavior in subshell:"
(
  echo "Inside subshell:"
  echo "  LOCAL_VAR: $LOCAL_VAR"
  echo "  EXPORTED_VAR: $EXPORTED_VAR"
  echo "  Creating subshell-only variable"
  SUBSHELL_VAR="This variable only exists in the subshell"
  echo "  SUBSHELL_VAR: $SUBSHELL_VAR"
)

echo -e "\nAfter subshell:"
echo "LOCAL_VAR: $LOCAL_VAR"
echo "EXPORTED_VAR: $EXPORTED_VAR"
echo "SUBSHELL_VAR: $SUBSHELL_VAR" ## This will be empty

## Creating a script to test export behavior
echo -e "\nCreating child script to test variable export..."
cat > ~/project/child_script.sh << 'EOF'
#!/bin/bash
echo "In child script:"
echo "EXPORTED_VAR: $EXPORTED_VAR"
echo "LOCAL_VAR: $LOCAL_VAR"
EOF

chmod +x ~/project/child_script.sh

## Run the child script
echo -e "\nRunning child script:"
./child_script.sh

This script demonstrates:

  1. Common environment variables (USER, HOME, PATH, etc.)
  2. The difference between local and exported variables
  3. Variable behavior in subshells (the parentheses create a subshell)
  4. How exported variables are inherited by child processes

Save the file with Ctrl+O and Enter, then exit nano with Ctrl+X.

Make the script executable:

chmod +x ~/project/environment.sh

Now run the script:

./environment.sh

The output will show you how variables behave in different contexts:

  • Environment variables are preset by the system
  • Local variables exist only in the current script
  • Exported variables are passed to child processes
  • Variables created in subshells aren't available in the parent shell

Understanding variable scope is crucial when writing complex scripts that spawn child processes or source other scripts. It helps you manage data flow between different parts of your system.

Summary

In this lab, you have learned the fundamentals of variable declaration and manipulation in Linux shell scripting. You have explored:

  • Basic variable declaration and usage
  • Integer variables and arithmetic operations
  • Array variables for storing collections of data
  • Variable manipulation techniques for text processing
  • Environment variables and variable scope

These skills form the foundation of shell scripting and are essential for automating tasks in Linux environments. Variables allow you to create more dynamic and flexible scripts by storing and processing data during execution.

You can now use these techniques to:

  • Store configuration settings in your scripts
  • Process user input and file contents
  • Manipulate text data and file paths
  • Share data between different scripts and processes

As you continue your journey in Linux shell scripting, you'll find that mastering variable usage opens up many possibilities for creating powerful and efficient automation tools.