Programming Constructs
------------------------------------------------------------------------------------------------------------------------------------------------
FOR LOOPS
For loops are a fundamental programming construct used to execute a block of code repeatedly. They are particularly useful when you need to process a sequence of items, like elements in a list or characters in a string.
Example:
#!/bin/bash
for filename in `seq 10` ##sets the variable filename as the output of seq 10
do
touch video$filename.mp4 ##create file video$filename.mp4
done
------------------------------------------------------------------------------------------------------------------------------------------------
WHILE LOOPS
While loops are another common programming construct for repeated execution of code blocks. They differ from for loops in how they determine how many times to run.
Example:
#!/bin/bash
filenum=10 ##variable filenum has a value of 10##
while [ $filenum -gt 0 ] ##while variable filenumber is greater than 0
do
touch vide$filenum.mp4 ##create a file video$filenum.mp4
filenum=$(($filenum -1)) ##change variable filenum to it's current value -1
done
In this example, a while loop is being used to create 10 files, all numbered, counting down from 10 until the value of 0 is reaching - meaning that 10 files are created.
------------------------------------------------------------------------------------------------------------------------------------------------
IF & ELSE Statement
An if statement is a fundamental building block in programming that allows you to control the flow of your code based on certain conditions. It's like a decision-making tool for your program.
if statements are opened with the if command, and closed with the fi command. Anything past the fi command will run regardless of the outcome of the if statement.
example:
#!/bin/bash
echo -e "Username: "
read username ##prompt user input for variable username
if
id -u $username > -1 ##if UID of the username (variable) is greater than -1
then
echo "That username already exists"
else ##Providing that the criteria defined by the IF statement isn't met, the else statement can proceed
echo -e "Username "
read fullname
echo -e "Password "
read password
sudo useradd -c "$fullname" $username =p $password
fi
done
------------------------------------------------------------------------------------------------------------------------------------------------
No Comments