Skip to content

Latest commit

 

History

History
87 lines (65 loc) · 2.2 KB

File metadata and controls

87 lines (65 loc) · 2.2 KB

Variables and Data Types

Declaring and Using Variables

In shell scripting, variables are used to store and manipulate data. Variable names are case-sensitive, and it is good practice to use uppercase letters for constant values and lowercase or mixed-case letters for variable names.

Declaring Variables

Variables can be declared using the following syntax:

variable_name=value

For example:

name="Keval"
age=20

In this example, we declare a variable named first_name and assign the value "Keval" to it. We then use echo to print the value of the variable.

Example 2: Concatenating Variables

#!/bin/bash

first_name="Keval"
last_name="Hingu"

full_name="$first_name $last_name"

echo "Full Name: $full_name"

Here, we declare two variables, first_name and last_name, and concatenate them into a new variable full_name.

String, Integer, and Array Operations

String Operations

Example 3: String Length

#!/bin/bash

full_name="Keval Hingu"

# Get the length of the string
length=${#full_name}

echo "Length of Full Name: $length"

In this example, we use the ${#variable} syntax to get the length of the string stored in the full_name variable.

Integer Operations

Example 4: Performing Integer Arithmetic

#!/bin/bash

# Declare integer variables
num1=10
num2=5

# Perform arithmetic operations
sum=$((num1 + num2))
difference=$((num1 - num2))
product=$((num1 * num2))
quotient=$((num1 / num2))

echo "Sum: $sum"
echo "Difference: $difference"
echo "Product: $product"
echo "Quotient: $quotient"

Here, we perform basic arithmetic operations on integer variables num1 and num2.

Array Operations

Example 5: Array Declaration and Usage

#!/bin/bash

# Declare an array
colors=("Red" "Green" "Blue")

# Access and print array elements
echo "First Color: ${colors[0]}"
echo "Second Color: ${colors[1]}"
echo "Third Color: ${colors[2]}"

In this example, we declare an array named colors and access its elements using index notation.

These examples illustrate the basics of declaring and using variables, as well as performing operations on strings, integers, and arrays in shell scripting. Feel free to modify and experiment with the provided code.