Linux bash shell Learning (9): Process Control -- If/else

Source: Internet
Author: User
Tags builtin

This article is the fifth chapter of Flow Control in learning the bash shell 3rd edition, but we will not limit it to this. Flow Control is a common part of any programming language and includes bash. Here we will learn about them.

If/else is used to determine whether to execute or execute part of the code. It can be determined based on variables, file names, whether the command is successfully executed, and many other conditions. Its format is as follows:

If

Condition

Then

Statements

[Elif

Condition

Then

Statements.

...]

[Else

Statements

]
Fi

Unlike C Programs, bash uses statement instead of Boolean to determine the final state (exit status) after the command is executed ). For all Linux commands, whether the code is C or script, after execution, an integer is returned to notify him of the call. This is the exit status, usually 0 indicates OK, others (1-255) indicate errors. This is only common. For example, diff, 0 indicates no difference, 1 indicates difference, and 2 indicates error. If judges the Last Exit status of statements, we usually put only one statement. If it is 0, it indicates true; otherwise, it indicates false.

Executing the next command will overwrite the original exit status. You can use $? To view the execution results of the previous command. For example, we want to use a new CD command to replace the CD command that has been compiled in Linux kernel. Because the function takes precedence over the built-in command, will call our function. In the following example, function pushd, type the dirname path of Cd in the stack, and run the following command to jump to the path.

CD ()

{

# Because we have defined a function with a higher priority, if you want to call the original built-in command, you need to add builtin.

Builtin

Cd "$ @"

# $? Is the return value of the previous command, that is, the value of builtin cd "$ @", which is recorded in the result.

Result =$?

Echo "$ oldpwd --> $ PWD"

# Return the value of result. We need to note that the return in shell is different from that in other programs. For example, the return in C language only represents the final exit statue, rather than the so-called return value, although return is also used. For example, push_func, the exit status is the exit status of the last executed command.

Return

$ Result

}

Push_func ()

{

Dirname = $1

# If dirname is null, exit funcuntion. If CD dirname is successful, push the directory. Otherwise, still in $ PWD is displayed. CD uses the function's CD function, the priority level is higher than that of the CD compiled in the kernel.

If

CD $ {dirname :? "Missing directory name ."}

Then

Mystack = "$ dirname $ {mystack:-$ oldpwd }"

Echo $ mystack

Else

ECHO still in $ PWD.

Fi

}

Push_func $1

Condition combination

Like the C language, conditions can be combined to use &, |, and! The format is as follows:Statement1

&&

Statement2,

IfStatement1

|

Statement2

, If!

Statement1

.

Exit status is not a unique value. You can use [...] and [...].

String comparison

String comparison is placed in [...], which has the following types:

  • Str1 = str2, string 1 matches string 2
  • Str1! = Str2, string 1 does not match string 2
  • Str1> str2, string 1 is greater than string 2
  • Str1 <str2, string 1 is smaller than string 2
  • -N str. the string is not null and the length must be greater than zero.
  • -Z Str. the string is null and the length is zero.

  Note that the <and> symbol is similar to the redirection symbol. To avoid ambiguity and errors, use if [$

/>

$ B

] Method

. In the above example, we add pop_func to operate the stack:

Pop_func ()

{

Mystack =$ {mystack #*}

# For details about [...], that is, [there is a space behind it,] There is a space before it, and $ mystack uses double quotation marks to indicate that this represents a string. Note that then is not placed in the next row, and is separated by a line with if.

If[-N "$ mystack"];

Then

CD $ {mystack % *}

Echo "$ PWD", stack is [$ mystack]

Else

Echo "Stack empty, still in $ PWD ."

Fi

}

For example, the command must contain parameters except {1? In addition to "<message"}, the following provides a more readable method:

If [-z "$1"]; then

Echo 'usage: C filename [-N]'

Exit

1

Fi

In this example, exit indicates that the operation is complete and exits. The execution result is "failed" and "non-zero.

File Property Comparison

File attributes are another common condition judgment type.

  • -

    File

    : File exists

  • -D

    File

    : File exists and is a directory

  • -E

    File

    : File exists, same as-

  • -F

    File

    : File exists and is a regular file (not a directory or another special type file)

  • -R

    File

    : Read Permission

  • -S

    File

    : The file exists and is not empty.

  • -W

    File

    : Write Permission

  • -X

    File

    : You have the execution permission or the search permission on the directory.

  • -N

    File

    : After the last read, the file has been changed.

  • -O

    File

    : File to which own belongs

  • -G

    File

    : File to which the Group belongs

  • File1

    -NT

    File2

    : File1 is better than file2. The last update time prevails.

  • File1

    -Ot

    File2

    : File1 is older than file2. The last update time prevails.

These are in [...] the condition judgment in can be combined with multiple conditions, for example, if [condition] & [condition]; then, of course, can also be if command & [condition]; then, and so on. In particular, we can determine the replication conditions. You can also use-

And-O

It is equivalent to the logical computation of & and | in C. They are similar to & that |. When they are used in condition.

In the above push_func example, in addition to determining whether a parameter is used, add a directory name, as shown below:

If[-N "$ dirname"] & [-d "$ dirname"]

Then

CD $ dirname

Mystack = "$ dirname $ {mystack:-$ oldpwd }"

Echo $ mystack

Else

ECHO still in $ PWD.

Fi

When adding a judgment, we checked whether the directory name can be viewed or operated. Use if [-n "$ dirname"] & [-D "$ dirname"-a-X "$ dirname"

], But this writing method is hard to read. We need to enclose the two before and after judgment (-d "$ dirname")-A (-X "$ dirname "). However, (it is a special match and requires the/(method, that is, if [-n "$ dirname"] &[/(-D "$ dirname"/)-A/(-X "$ dirname"/)]

.

Integer comparison

> Or <OR = is used for string comparison. If used for integer comparison, use:

  • -Lt, less
  • -Le, less than or equal
  • -EQ, equal
  • -Ge, greater than or equal
  • -GT, greater
  • -Ne, not equal

Related links:
My articles on Linux operations


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.