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.
Variables can be declared using the following syntax:
variable_name=valueFor example:
name="Keval"
age=20In 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.
#!/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.
#!/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.
#!/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.
#!/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.