17. Self-Learning Linux path: Conditional judgment statement for Bash programming

Source: Internet
Author: User

BASH Programming Conditional judgment: Determine whether the prerequisites for subsequent operations are satisfied

Common Types of Judgments:

Integer judgment:

Character Judgment:

File judgment:

$?: Status return value

0: True

1-255: Fake

We can use the status return value as the judging condition, do not need to add ' '

Boolean value:

True and False

Logical operation:

and Operation:&&

Or Operation: | |

Non-op:!

The conditions in bash are judged using if:

Single branch:

if condition; Then

Branch 1;

Fi

Dual Branch:

if condition; Then

Branch 1;

Else

Branch 2;

Fi

Multi-branch:

if condition; Then

Branch 1;

Elif Condition 2; Then

Branch 2;

elif condition 3; Then

Branch 3;

.

.

Else

Branch N;

Fi

Exercise: 1. Let the user specify a file, determine: If the file has a blank line, the number of blank lines is displayed

Nano spaceline.sh

#!/bin/bash

#

Read-p "Enter a file path:" Fliename

If grep "^$" $fileName &>/dev/null; Then do not add ' because we are not using the result of the command but the command state return value

Linescount= ' grep ' ^$ ' $fileName | Wc-l '

echo "$fileName has $linesCount space lines."

Fi

Exercise: 2. Let the user specify a file, determine: If the file has a blank line, the number of blank lines will be displayed, otherwise there will be no blank line output

CP spaceline.sh spaceline2.sh

Nano spaceline2.sh

#!/bin/bash

#

Read-p "Enter a file path:" FileName

If grep "^$" $fileName &>/dev/null; Then

Linescount= ' grep ' ^$ ' $fileName | Wc-l '

echo "$fileName has $linesCount space lines."

Else

echo "$fileName have no space lines"

Fi

17. Self-Learning Linux path: Conditional judgment statement for Bash programming

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.