If Else statement while statement in the shell

Source: Internet
Author: User

The shell can use "[]" to judge data, and "[]" is basically consistent with test.

When using "[]" pay attention to three points (from Brother Bird):

1, in the brackets "[]" in each component needs to have the space bar to split.

2, in the brackets inside the variables, preferably in double quotes around.

3. Constants in brackets, preferably enclosed in single or double quotes

The structure of the IF Else statement is:

if [condition]; Then

#some statements

elif [condition]; Then

#some statements

Else

#some statements

Fi

Here is a small example, where ["$yn" = = "Y"] | | ["$yn" = = "Y"] is equivalent to ["$yn" = = "Y"-o "$yn" = = "Y"], "o" means "or", connecting two judgements.

#!/bin/bash

#read user ' s input and do something
read-p "please input (y/n):" Yn

if ["$yn" = = "Y"] | | ["$yn" = = "Y"]; Then
        echo "OK, you say yes."
elif ["$yn" = = "N"] | | ["$yn" = = "n"]; Then
        echo "NO? Goodbye. "
else
        echo "I don ' t know what you say"
fi

#test whether a directory exist,if not,create it
if [! d] Keys Toneclient "]; Then
        mkdir keystoneclient
fi

The basic structure of the while statement is:

While [condtion]

Todo

#some statements

Done

Here is a small example:

#!/bin/bash while

["$yn"!= "yes"-a "$yn"!= "yes"
does
        read-p "please input Yse/Yes to stop this loo P. "Yn
do

echo" OK, you input the correct answer.
Adding a sleep statement in the while statement constructs a simple timer, and the sleep unit is seconds. For the following example, print the time every second.

#!/bin/bash while

[1]
does
        date sleep
        1
done



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.