Skip to content

Latest commit

 

History

History
51 lines (38 loc) · 2.22 KB

1.md

File metadata and controls

51 lines (38 loc) · 2.22 KB

Chapter 2: The Variable Verse 🌌

1 - The What, Why and How's of varibles in linux

What are variables?

Variables in shell scripting serve as containers for storing information, which can be characters, numeric, or alphanumeric values. They represent memory locations in the system and are accessed and manipulated by referencing their variable names. In shell scripting, variables are referenced by combining the variable name with the dollar sign ($), such as $VARIABLE_NAME.

Why use variables?

Variables provide a convenient way to store and manage data within shell scripts. They allow scripts to dynamically access and modify values, improving code readability and maintainability. By using variables, shell scripts can efficiently handle various types of information, making them essential for automating tasks and performing system operations.

How to use variables?

In shell scripting, variables are assigned values using the syntax VARIABLE_NAME=VALUE. Some rules for using variables in shell scripting include:

  • Use the equal sign (=) to assign values to variable names.
  • Variable names are case-sensitive; 'A' and 'a' are considered different variables.
  • To reference a variable, prepend the variable name with a dollar sign ($), e.g., $VARIABLE_NAME.
  • When updating variable values, only the variable name and the new value are required, using the assignment operator (=), e.g., VARIABLE_NAME=NEW_VALUE.
  • There's no need to declare variable types in shell scripting.
  • To handle multiple words or string values, enclose them within single quotes (' ') to preserve all characters as input.

Here's a simple example demonstrating the use of variables in a Linux shell script:

#!/bin/bash

# Define variables
NAME="John"
AGE=30
CITY="New York"

# Print variables
echo "Name: $NAME"
echo "Age: $AGE"
echo "City: $CITY"

# Combine variables
GREETING="Hello, my name is $NAME. I am $AGE years old and I live in $CITY."
echo $GREETING

When you run this script, it will output:

Name: Bruce
Age: 45
City: Gotham
Hello, my name is Bruce. I am 45 years old and I live in Gotham.

⬅️Previous-----------Next ➡️

Table of contents 🚀