Get the App
SLTechnology News&Howtos  ›  Servers  › 

Carding the basic knowledge of shell script & lt; III & gt;: conditional Test and comparison, process Control if

Shulou Source: shulou.com Published: 2022-06-02 16:27:58 09月17日 Update

I. conditional testing and comparison

1. Test test expressions are commonly used

Test-f file & & echo true | | echo false

2. [test expression] is very commonly used

[- f file] & & echo true | | echo false

3. [[test expression]]

II. Process control

1. Flow control statement if

Example 1

#! / bin/bash

# get 0 in uid=0 (root)

Id=id | awk-F'[= (]'{print $2}')

Echo "your user id is:$id"

If [$id-eq 0]

Then

Echo "root"

Else

Echo "not root"

Fi

Example 2: determine the logged-in user

#! / bin/bash

# $# is the number of parameters added to shell

If [$#-eq 1] # or [[$# = = 1]] or ($# = = 1)

Then

If who | grep $1 > / dev/null

Then

Echo $1 is active.

Else

Echo $1 is not active.

Fi

Else

Echo "Usage: $0"

Exit 1

Fi

~

The result after execution

[root@localhost shell] # sh if-if.sh root

Root is active.

[root@localhost shell] # sh if-if.sh zabbix

Zabbix is not active.

[root@localhost shell] # sh if-if.sh

Usage: if-if.sh

[root@localhost shell] #

Instance 3 if-elif..else-fi

#! / bin/bash

# # if-elif..else-fi

Read-p "how lod are you?" Age

# conditional testing using the shell arithmetic operator (())

If ((age120)); then # [age

< 0 || age >

120]]

Echo "out of range!"

Exit 1

Fi

If ((age > = 0&&age=13&&age=20&&age=30&&age)

Tags: Tests examples expressions conditions controls commonly used results statements processes numbers Writing parameters users operators errors logins Operations Basics Basics knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Microsoft MariaDB macOS OPPO Reno