An Analysis of IF Statements in shell scripts

Source: Internet
Author: User

A shell script must have been written as follows:

If [-D dir]
Then
Echo "success"
Else
Echo "failed"
Fi

When talking about if, the book will mention the following two rules:
1. There must be spaces on the left of "[" and;
2. If you want to put then and if in the same row, add a semicolon to writeIf [-D/bin]; thenThis form.

Most of the books have been introduced here, and I once memorized these two rules. I still think that shell scripts are irregular, hard to remember, and hard to write. In fact, it wasn't until today that I found out:

Roovent @ Ubuntu-desktop :~ $ Which [
/Usr/bin /[

Original"[" Is a commandIs a command like LS and RM. After investigation, the "[" command and the test command have the same functions and usage. In some versions of Linux, "[" is a link of test.
This explains, [-D is actually a command with a parameter, like LS-A. Of course, there must be spaces between the command and the parameter. "[" Is a little special. Its last parameter must be "]", and there must be spaces between parameters. This is a good explanation of the first rule. To put then and if in the same line, add a semicolon after "]" to tell the end of the "[" command, otherwise then will be treated as the last parameter.
Well, it turns out that everything is so reasonable. The shell script designer won't be able to find things so complicated, but the strange command name "[" is not acceptable.
Let's just say,If can be followed by various statementsFor example, if ECHO "Hello" is also valid, and the judgment is based on whether the statement is successfully executed. Of course, if followed by multiple statements connected with & or | can also be used.

-----------------------------------------------------
-OriginalArticle, Reprinted, please indicate the source.
-Boke Park: http://www.cnblogs.com/roovent/
-Baidu: http://hi.baidu.com/roovent/home Space
-Email: yangq. nj # gmail.com
-----------------------------------------------------

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.