You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# Declaring variables
name="John"
age=30
# Using variablesecho"My name is $name and I'm $age years old"# Command substitution
current_date=$(date +%Y-%m-%d)# Arithmetic operations
result=$((5+3))
Conditionals
# If statementif [ "$a"-eq"$b" ];thenecho"a is equal to b"elif [ "$a"-gt"$b" ];thenecho"a is greater than b"elseecho"a is less than b"fi# Case statementcase"$variable"in
pattern1) command1;;
pattern2) command2;;
*) default_command;;
esac# Check number of command line argumentsif [ "$#"-eq 2 ];thenecho"Exactly two arguments provided"elif [ "$#"-lt 2 ];thenecho"Less than two arguments provided"elif [ "$#"-ge 2 ];thenecho"Two or more arguments provided"fi
Loops
# For loopforiin {1..5};doecho$idone# While loop
counter=0
while [ $counter-lt 5 ];doecho$counter((counter++))done# Until loopuntil [ $counter-ge 5 ];doecho$counter((counter++))done
# Read user inputread -p "Enter your name: " name
# Write to fileecho"Some text"> file.txt
# Append to fileecho"More text">> file.txt
# Read from filewhile IFS= read -r line;doecho"$line"done< file.txt
Arrays
# Declare an array
fruits=("apple""banana""cherry")
# Access array elementsecho${fruits[0]}# First elementecho${fruits[@]}# All elements# Array lengthecho${#fruits[@]}
# Check if file existsif [ -f"$file" ];thenecho"File exists"fi# Check if directory existsif [ -d"$dir" ];thenecho"Directory exists"fi# Check if command existsifcommand -v jq &> /dev/null;thenecho"jq is installed"fi# Print a # character across the terminal. (visual separator)printf -v separator '%*s'$(tput cols)''&&echo"${separator///#}"