0% found this document useful (0 votes)
13 views18 pages

Lect 17

Uploaded by

ixvvy1012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views18 pages

Lect 17

Uploaded by

ixvvy1012
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

05‐Oct‐24

[17] Bash with Conditions

CMPS 101 : Introduction to Computer Science


Fall 2024
Eng. Amelle Bedair, [email protected]

Lab Exam. 10 Oct ‐ Hands‐on coding


Material: Labs [1‐6]
Section B52 starts at 09:00
Section B53: Starts at 13:00

1
05‐Oct‐24

Mid‐Term Exam. Online MCQ. Bring your laptop


Date: Sunday; 13‐Oct‐2024
Material: Lect. [2‐16]
Support: Labs [1‐6]

Topics
• Decision Making
• The if-then statement
• The if-then-else statement
• Garbage-in / garbage-put
• User input validation

2
05‐Oct‐24

Decision making is the process of evaluating


alternatives and selecting an action.

If I have more
than 50 QR, I will
buy a
cheeseburger.

true no action
Is money > 50 QR?
condition is satisfied
If the result of the
condition = false,
there will be no
action

3
05‐Oct‐24

If I have more than condition: having more than 50


50 QR, then I will
buy a cheeseburger.
Otherwise, I will buy 2 actions:
some biscuits.
true false
Is money > 50 QR?

Bash if statement
• When coding, you might need to make decisions based on certain
conditions.
• Conditions are expressions that evaluate to a Boolean expression
(true or false).
• Bash supports two versions of conditions;
bash have
2 types of • The if‐then else
decision • The if‐then‐else then
making

if

4
05‐Oct‐24

The Bash if‐then Statement


if [ condition ]
key words then
# Action when the condition is true
fi means this is my decision concept
Notes
• There should be a space after the opening bracket [ and before
the closing bracket ] in your conditions. This is necessary for [ ]
to function properly as a test command.
• The if, then, and fi are keywords. You should not use them
as variable names.

if [ condition ]
then pushing called indented
pushing the statement
a bit # Action when the condition is true
fi

The syntax shows the following;


• The if‐then is a block which starts with an if keyword and
terminates with a fi keyword, i.e. the if and fi indicate the
boundaries of the block
• After the then keyword, lines are indented, i.e. there are few
spaces before each action statement. This spacing are not
mandatory, but recommended. The aim is to improve
readability and make it harder for us to make silly mistakes.

5
05‐Oct‐24

for 2 actions

The Bash if‐then‐else Statement


if [ condition ]
then this action will be executed if the cond. is true
# Action when the condition is true
else otherwise
# Action when the condition is false
fi

In the Action sections, lines are indented, i.e. there are few
spaces before each action statement. This spacing are not
mandatory, but recommended for clarity.

Numeric Comparison Operators


only work with an integer : whole number
These operators compare integer values:
• ‐eq: Equal to.
• ‐ne: Not equal to . if [ $n1 ‐eq $n2 ]
then
• ‐lt: Less than. echo "The numbers are equal"
• ‐le: Less than or equal to. fi
• ‐gt: Greater than.
• ‐ge: Greater than or equal to.

6
05‐Oct‐24

The Division Remainder

In mathematics, division with remainder


refers to dividing one integer by another
and getting a quotient along with a
remainder.
• Quotient: The result of the division.
• Remainder: The part of the dividend that
is left over after division.

modulus operator calculate


work only with integer
Arithmetic Expansion $((…))
Performing basic arithmetic operations such as addition, subtraction,
multiplication, and division is essential for many scripting tasks. These
operations can be used to increment a counter, calculate percentages
or totals, or determine if a number is even or odd.
Place an integer arithmetic expression inside double parenthesis and
place a dollar mark before the parenthesis, i.e. $((expression)).
Examples;
• y=$((5+3)) # y=3+5
• y=$((5+$a)) # y=5+a
• y=$((5%2)) # modulus operation i will know if it is odd or even

7
05‐Oct‐24

Odd or Even

• One common thing to do with conditionals is to check if a number is


odd or even.
• If you divide any number by 2, then;
• If the remainder is 0, then the number is even
• If the remainder is 1, the number is odd,
• You can calculate the remainder with the modulo operator % like
this:‐ num % 2

Example: The following code (ex.sh) is an example script (code) that will
prompt you to input a number and then it checks whether the given
number is even.

#!/usr/bin/bash
# Prompt the user to enter a number
read ‐p "Enter Number: " n
# Check if the entered number is even
if [ $((n % 2)) ‐eq 0 ] $ bash ex.sh
then Enter a number: 6
echo " The number is even " The number is even
fi $

$ bash ex.sh
Enter a number: 5
$

8
05‐Oct‐24

Example: The following code (ex.sh) is an example script (code) that will
prompt you to input a number and then it checks whether the given
number is odd or even.
#!/usr/bin/bash
$ bash ex.sh
read ‐p "Enter Number: " num
Enter a number: 16
if [ $((num%2)) ‐eq 0 ] The number is even
then $
echo "The number is even"
else $ bash ex.sh
echo "The number is odd" Enter a number: 15
The number is odd
fi
$
echo "========================"

Example: The following code (ex.sh) is an example script (code) that will prompt you
to input a number and then it checks whether the given number is odd or even.

#!/usr/bin/bash
read ‐p "Enter Number: " num $ bash ex.sh
Enter a number: 6
if [ $num ‐ge 0 ]
The number is positive
then $
pushed echo "The number is positive"
to make clear that this is an action
else
$ bash ex.sh
echo "The number is negative" Enter a number: ‐9
fi The number is negative
$
echo "========================"

9
05‐Oct‐24

In the previous examples, the action section contained only one


command. However, you cam combine many commands to create
scripts capable of automating complex tasks and processes.

if condition
then align the commands
command1
command2
command3
...
commandN
fi useful for automation
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////

if condition1
multiple if > multiple conditions
then
Action1
You can also put multiple if‐ fi
then statements in sequence.
if condition2
The next slide shown an then
example in which Bash can Action2
state the relation between fi
two numbers; greater than,
less than, or equal. if condition3
then
Action3
fi

nested if is a an if inside if > it's not for us

10
05‐Oct‐24

Example: Edit Bash code (ex.sh) to prompt for two integers.


Then, it should display a message indicating which has the larger value.
Special case: When both values are equal, then the code states it
3 if statements
$ bash ex.sh
Enter first number: 5
Enter second number: 2
The first number is larger
$

$ bash ex.sh $ bash ex.sh


Enter first number: 5 Enter first number: 5
Enter second number: 8 Enter second number: 5
The second number is larger They are equal
$ $

no sub small connection btw the two commands

#!/usr/bin/bash
read ‐p "Enter first Number: " n1 $ bash ex.sh
read ‐p "Enter second Number: " n2 Enter first number: 5
Enter second number: 2
if [ $n1 ‐gt $n2 ] The first number is larger
1 then $
echo " The first number is larger "
fi $ bash ex.sh
if [ $n1 ‐lt $n2 ] Enter first number: 5
then
Enter second number: 8
2 The second number is larger
echo "The second number is larger"
$
fi
if [ $n1 ‐eq $n2 ]
$ bash ex.sh
then Enter first number: 5
3
echo "They are equal" Enter second number: 5
fi They are equal
$
echo "========================"

make sure that at anytime only one condition is correct

11
05‐Oct‐24

Note: The odd/even code sample does not handle cases where the
user enters a non‐numeric value. If the user enters a non‐numeric
value, it may produce unexpected results.
it can understand the letters so it will count it
as a zero > that is why the output is even
$ bash b1.sh
Enter Number: abc
The number is even
$

The reason your script is outputting "The number is even" when you
enter abc, is that the script might simply be treating it as 0 (which is
considered even). Additional input validation could be added to
address this.

Garbage In – Garbage Out

One of the most famous saying among computer programmers is “garbage in,
garbage out”. This saying, sometimes abbreviated as GIGO, refers to the fact that
computers cannot tell the difference between good data and bad data. If the user
provides bad data as input to a program, the program will process that bad data
and, as a result, will produce bad data as output.

12
05‐Oct‐24

Programmer vs. User


the one doing the program like nurse
Programmer Users
The users
can make
mistakes

protect their code from bad data

In general users are the ones that are supposed to use an application
(program) and programmers are the ones that develops an application
to fulfill the needs of users. 8888888888888888888
/////////////////////////////////////
8888888888888888888
////////////////////////////////////
8888888888888888888
////////////////////////////////////
8888888888888888888

Input Validation

It is important to protect the program from bad data by inspecting user


input first. If this input is invalid, the program should either terminate
program execution or prompt the user to re‐enter valid data. This
process is known as input validation. check if it is in the acceptable range

13
05‐Oct‐24

Input Validation

While writing a Bash Script, sometimes it becomes important to do


calculations based on user’s inputs. Let us see how to validate
numerical input.
Examples;
• This is not an integer
• This is not a floating‐point number
• This is not a positive number
• This is a 0
• This number is too small / too large

Integer Regular Expression


What is the meaning of the following regular expression (regex)
start
^[0‐9]+$ one or more combination
• The (^) indicates the start of the string.
• The [0‐9] specifies any digit between 0 and 9. validate any integer number

• The (+): means "one or more" of the preceding element, so it


matches one or more digits.
• The ($) the end of the string
Conclusion: The regex checks whether the entire string consists only of
digits.

14
05‐Oct‐24

Negating Conditions
You can negate (convert true to false or false to true) conditions
by using the ! operator.

if [ condition ]
then
# Action when condition = true
means not
fi
if ! [ condition ]
then
!false=true # Action when condition = false
fi
if the condition is false then the action will happen

now how to read the command

To check an integer, use the following condition:


not this one (expreesion)
if ! [[ "$num" =~ ^[0‐9]+$ ]]
matches

Where:
• The ! negates the condition, if the condition = false, then !false
is true.
• The condition matches the regex with the value of the variable num.
• The =~ operator is used to perform pattern matching with regular
expressions
• The double square brackets provide several features not available in
single square brackets, e.g. regular expression pattern matching.

15
05‐Oct‐24

The Bash code to validate user input as an integer number

#!/usr/bin/bash
read ‐p "Enter an integer: " num

# Check if the input is a valid integer using regex


# The ! is NOT. Add a space before and after
if ! [[ "$num" =~ ^[0‐9]+$ ]]
then
echo "Error: Not a valid integer."
exit 1
else means stop doing it
echo "OK"
fi
echo "========================"

$ bash ex.sh
Enter an integer: 5
The number is odd
========================
$ bash ex.sh
Enter an integer: 4
The number is even
========================
$ bash ex.sh floating point > dot is not acceptable since i didn't tell
Enter an integer: 2.8
Error: '2.8' is not a valid integer.
========================
$ bash ex.sh
Enter an integer: abc
Error: 'abc' is not a valid integer.
========================

16
05‐Oct‐24

Example

$ bash age.sh
What is your name? Huda
What is your year of birth? 1800 User input
===========================
Thank you Huda.
You are 224 years old.

As shown above, the user second input (year of birth) is an


integer but with a non‐realistic value. This value may be further
processed leading to invalid results. As a programmer, you have
to protect the code from bad inputs.

always protect yr program from bad data

The Bash code to validate the year of birth


#!/usr/bin/bash
read ‐p " Name?: " name
read ‐p " Year of birth? " yob
# Calculate the age
age=$((2024‐yob))
# Check the age. Invalid age > 120 years
if [ $age ‐gt 120 ]
then
echo "Error: Not a valid year of birth"
exit 1
else
echo "Hello $name"
echo "You are $age years old"
fi
echo "========================"

17
05‐Oct‐24

18

You might also like