Skip to main content

Command Palette

Search for a command to run...

Shell Scripting

Published
•2 min read•View as Markdown

Bash - improved version of sh

Variables

#!/bin/bash

name="Anurag"  

echo $name

file_name="setup.yaml"
config=$(ls /bin)  

echo "$file_name and config in $config"

If-Else

if [ -d "temp1" ]
then
    echo "reading it"
else
    echo "NOT FOUND"
    mkdir temp1
fi

echo "all okay"

Operators

Arithmetic

#!/bin/bash

# Arithmetic operators
a=10
b=5

# Addition
result=$((a + b))
echo "Addition: $result"

# Subtraction
result=$((a - b))
echo "Subtraction: $result"

# Multiplication
result=$((a * b))
echo "Multiplication: $result"

# Division
result=$((a / b))
echo "Division: $result"

# Modulo (Remainder)
result=$((a % b))
echo "Modulo: $result"

Realational

#!/bin/bash
# Relational operators
x=10
y=5

# Equal to
if [ $x -eq $y ]; then
  echo "x is equal to y"
fi

# Not equal to
if [ $x -ne $y ]; then
  echo "x is not equal to y"
fi

# Greater than
if [ $x -gt $y ]; then
  echo "x is greater than y"
fi

# Less than
if [ $x -lt $y ]; then
  echo "x is less than y"
fi

# Greater than or equal to
if [ $x -ge $y ]; then
  echo "x is greater than or equal to y"
fi

# Less than or equal to
if [ $x -le $y ]; then
  echo "x is less than or equal to y"
fi

Logical

#!/bin/bash
# Logical operators
p=true
q=false

# Logical AND
if [ $p = true ] && [ $q = true ]; then
  echo "Both p and q are true"
else
  echo "At least one of p and q is false"
fi

# Logical OR
if [ $p = true ] || [ $q = true ]; then
  echo "At least one of p and q is true"
else
  echo "Both p and q are false"
fi

# Logical NOT
if ! $p; then
  echo "p is false"
fi

String

#!/bin/bash

# String assignment
string1="Hello"
string2="World"

# Concatenation
concatenated="${string1} ${string2}"
echo "Concatenated string: ${concatenated}"

# String length
length=${#string1}
echo "Length of string1: ${length}"

# Substring extraction
substring=${string1:0:3}
echo "Substring of string1: ${substring}"

# String comparison
if [ "$string1" = "$string2" ]; then
  echo "Strings are equal"
else
  echo "Strings are not equal"
fi

# String containment
if [[ "$string1" == *"He"* ]]; then
  echo "String1 contains 'He'"
else
  echo "String1 does not contain 'He'"
fi