Get the App
SLTechnology News&Howtos  ›  Servers  › 

What are several common writing methods of if judgment in Shell

Shulou Source: shulou.com Published: 2022-06-01 18:38:29 09月16日 Update

This article mainly explains "what are several common ways to write if judgment in Shell". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let Xiaobian take you to learn "what are the common ways to judge if in Shell"!

If, for, while is almost all programming language keywords, in Shell programming is no exception, where if is the most frequently used, because Shell programming does not exist in the concept of object (Object), so in the comparison judgment of if is mainly to string, numerical value comparison judgment:

I. Basic syntax of if

There must be a space between if and [

There must also be a space between [] and the judgment condition

There cannot be a space between] and;

II. Judgement of string

if [ str1=str2 ];then fi #Returns true if two strings are the same

if [ str1!= str2 ];then fi #Returns true if two strings are not equal

if [ -n str1 ];then fi #Returns true if the length of the string is greater than 0 (determines whether the variable has a value)

if [ -z str1 ];then fi #Returns true if the string length is 0

III. Judgment of numbers

int1 -eq int2 #int1 and int2 are equal

int1 -ne int2 #int1 is not equal to int2

int1 -gt int2 #int1 is greater than int2

int1 -ge int2 #int1 is greater than or equal to int2

int1 -lt int2 #int1 is less than int2

int1 -le int2 #int1 is less than or equal to int2

IV. Judgment of file attributes

-r file #User readable is true

-w file #user can write true

-x file #user executable is true

-f file #file exists and is regular file is true

-d file #True if directory exists

-c file #file exists and is a character device file

-b file #file exists and is a block device file

-s file #file size is not 0 is true, you can determine whether the file is empty

-e file #True if file exists

v. logical judgment

-a #and

-o #or

! #Not

At this point, I believe that everyone has a deeper understanding of "what are several common ways to judge if in Shell". Let's do it in practice! Here is the website, more related content can enter the relevant channels for inquiry, pay attention to us, continue to learn!

Tags: File character string writing common between user programming two content number device length learning practical deeper highest regular same key Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi MySQL macOS Huawei MariaDB