Bash_mid_Adv

Rudresh SinghRudresh Singh
5 min read

We have already covered the variables — but just for refreshers…

1. Variables

Basics:

#!/bin/bash

# Variable assignment
name="Alice"
echo "Hello, $name!"

# Read input from the user
echo "Enter your name:"
read user_name
echo "Hello, $user_name!"

2. Conditional Statements

If-Else:

#!/bin/bash

number=10

if [ $number -gt 0 ]; then
    echo "The number is positive."
elif [ $number -lt 0 ]; then
    echo "The number is negative."
else
    echo "The number is zero."
fi

working :

if[condition]; then // similar to other programming — se if also represents the start of the block here

print something or do something elif [conditon] // elif == else if

print something or do something

else

print something

fi // represents the end of the block

-gt — here represents greater than

-lt — this represents less than

there are many others like
-eq — for equal

-ne — not equal

-ge —greater than equal

-le —less than equal

instead of these you can use arithmetic too

#!bin/bash

echo "enter num" 
l
read number

if (( $number > 0 )); then
    echo "The number is positive."
elif (( $number < 0 )); then
    echo "The number is negative."
else
    echo "The number is zero."
fi

Case Statements:

#!/bin/bash

echo "Enter a number between 1 and 3:"
read number

case $number in
    1) echo "You entered one." ;;
    2) echo "You entered two." ;;
    3) echo "You entered three." ;;
    *) echo "Invalid number." ;;
esac

3. Loops

For Loop:

#!/bin/bash

for i in {1..5}; do
    echo "Iteration $i"
done

# Iterating over a list
for names in aditya rudresh shlok vedant mai tum hum do
    echo "useless $names."
done

see we all know for is generally used as counter, as usual we will be having the iterator i in range {1..5}; — see {1 to 5 } is range hope you got it this way too much spoon feeding

now coming to reading the list/array using using the for loop —- see we all are aware of for each loop it’s similar to that

see till now we don’t know how to make array so we will be creating temp array

like here
for names in adiya rudresh shlok vedant ``do
see we have created the list of names now under names variable
—-by just putting names under the for loop we can access each elements in names

While loop:

#!/bin/bash

counter=1
while [ $counter -le 5 ]; do
    echo "Counter: $counter"
    ((counter++))
done

similar to while loop in other languages nothing fancy

you will have
while((codition)); do

something....

done

do act as start of the block { and —- done act as the end of the block }

4. Functions

Basic Functions:

#!/bin/bash

print() {
    echo "Hello, $1!"
}

print "Aditya"
print "Rudresh"
print "Shlok"

see you can call any function like this Working — see our function taking only arguments we already has covered arguments—so $1 is acting as an argument and 1 represents only argument

and with function call print we are passing one parameter eg :

print "Aditya": Calls the print function with "Aditya" as the first argument. $1 within the function will be "Aditya". Return Function—

See there is NO Concept of return in bash for NON-INTEGERS So,

there are several ways to do this For INT To return an integer value indicating the success or type of error. Typically used to indicate whether a function has completed successfully (0) or encountered an error (non-zero).

Example:

#!/bin/bash

# Function to check if a number is even or odd
check_even_odd() {
    if (( $1 % 2 == 0 )); then
        return 0  # Even
    else
        return 1  # Odd
    fi
}

# Call the function
check_even_odd 4
result=$?

if [ $result -eq 0 ]; then
    echo "The number is even."
else
    echo "The number is odd."
fi

Explanation:

  • return 0: Sets the exit status to 0 if the number is even.

  • return 1: Sets the exit status to 1 if the number is odd.

  • $?: Captures the exit status of the last executed command or function And see if it’s not int you have to do some tricks in bash to return value you can’t have return type or return value here (except int) , like echo the result and then capture it, or make result global Variable……..

    i) Command Substitution

    To return strings or more complex values by capturing the output of a command or function.

      #!/bin/bash
    
      # Function to add two numbers and return the sum
      add_numbers() {
          local sum=$(( $1 + $2 ))
          echo $sum
      }
    
      # Call the function and capture the output
      result=$(add_numbers 3 5)
      echo "Sum: $result"
    

    Explanation:

    • echo $sum: Outputs the result of the addition.

    • result=$(add_numbers 3 5): Captures the output of the add_numbers function.

ii) Global Variables

To store the result of a function in a global variable accessible outside the function.

    #!/bin/bash

    # Function to multiply two numbers and store the result in a global variable
    multiply_numbers() {
        result=$(( $1 * $2 ))
    }

    # Call the function
    multiply_numbers 4 7
    echo "Product: $result"

Explanation:

  • result=$(( $1 * $2 )): Stores the result of the multiplication in a global variable result

    see result here is global variable as we have already seen the for defining local variable within function we need to put
    local Keyword so result var here is global hence we can access it from anywhere

    5. Arrays

    Declaring and Accessing Arrays:

      #!/bin/bash
    
      # Declare an array
      names=("aditya" "shlok" "Rudresh")
    
      # Access elements
      echo "harami 1: ${names[0]}"
      echo "harami 2: ${names[1]}"
      echo "harami 3: ${names[2]}" 
    
      #TO access single element in array
      echo "who is ${names[0]}"
    
      #how to know array length??
      echo "lenth of total ${#names[@]}" 
      # Iterate over array
      for names in "${names[@]}"; do
          echo "I like $names."
      done
    

    so you can access names by accessing every single element or by entire array by putting array length in for loop.

i think we have covered all the basics med level of the bash — few things left like

error handling (which you can do by if else or set condtion1 condtion2 — and file operations

  • although we have done file operation in our practice session but still We will cover this in Advance section..
0
Subscribe to my newsletter

Read articles from Rudresh Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rudresh Singh
Rudresh Singh