How to use IF statements in bash scripts _linux shell

Source: Internet
Author: User
Tags echo name

In addition to the "If,else" form, there are other forms of "if" statements:

Copy Code code as follows:

if [condition]
Then
Action
Fi

The statement performs an action only if condition is true, otherwise the operation is not performed and any rows after "fi" are resumed.

Copy Code code as follows:

if [condition]
Then
Action
elif [Condition2]
Then
Action2
.
.
.
elif [Condition3]
Then
Else
ActionX
Fi

The above "elif" form will continuously test each condition and perform an operation that conforms to the first true condition. If no condition is true, the "Else" action is executed, and if one condition is true, the line following the entire "If,elif,else" statement continues.

Receive self variable

In the sample program in the introductory article, we use the environment variable "$" to refer to the first command-line argument. Similarly, you can use "$", "$", and so on to refer to the second and third arguments passed to the script. Here's an example:

Copy Code code as follows:

#!/usr/bin/env Bash
echo name of script is $
echo-argument is $
Echo second argument is $
Echo Seventeenth argument is $17
echo number of arguments is $#

In addition to the following two details, this example does not need to be explained. First, "$" expands to the name of the script that is invoked from the command line, and "$#" expands to the number of arguments passed to the script. Test the above script to understand how it works by passing different types of command line arguments.

It is sometimes necessary to refer to all command-line arguments at once. For this purpose, bash implements the variable "$@", which expands to all command line arguments separated by spaces. In the "for" loop section later in this article, you'll see an example of using that variable.

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.