How to use if and for statements in bash scripts

Source: Internet
Author: User

How to use if and for statements in bash scripts

In the bash shell script, we need to understand three execution sequences first.

  • Sequential execution (from left to right, from top to bottom)
  • Select execution (a structure is executed only when the conditions are met or not met)
  • Loop execution (repeated execution of a segment structure)

The if statement written today is "select order", and "for" indicates loop execution.

Some structures are inevitable in if or for and some calculation methods are required. I will first list them for future use.

Arithmetic Operation Method:

1. $ [expression]

The expressions can be composed of numbers only or variables can be used to reference variable values. When using variables, You can omit the $ symbol;

Example:

# Echo $[3 + 4]

# NUM1 = 5; NUM2 = 4; echo $[NUM1 * NUM2]

2. let VAR = EXPRESSION

Performs arithmetic operations based on arithmetic expressions and assigns values to specified variables;

3. $ (EXPRESSION ))

The expressions can be composed of numbers only or variables can be used to reference variable values. When using variables, You can omit the $ symbol;

4. expr ARGU1 ARGU2 ARGU3

ARGU1 and ARGU3 must be integer values, and ARGU2 must be Arithmetic Operators;

5. echo "EXPRESSION" | bc

6. bc <EXPRESSION

Location Parameter variables:
$0: The command itself. For a script, it is the path of the script;
$1, $2... $ n: the command line parameters passed to the script through the command line;
N> 9, When referencing the location variable, you need to add {}, that is, $ {10}

Special variables:
$ @: List of all location parameters. Each parameter exists as a separate string when double quotation marks are used;
$ *: A list of all location parameters. When double quotation marks are used for reference, the entire parameter list is treated as a string;
$ #: Identify the number of parameters in the command line except $0;

Shift command, you can set $2-> $1;

If statement:
If: if command; then Command; [elif command; then Command;]... [else command;] fi

The single branch structure of the if statement:
If command; then Command; fi

Note: whether the command after then will be executed depends on the return value of the execution status of the command after if;
1. If the returned value is true, run the command after then;
2. If the receipt is false, the command after then is not executed;

It is recommended that the writing format in the script be:
If CONDITION; then
STATEMENT
..
Fi

Or
If CONDITION;
Then
STATEMENT
..
Fi

If statement dual-branch structure:
If command; then Command; else command; fi

Note: whether the command after then or else will be executed depends on the return value of the execution status of the command after if;
1. If the returned value is true, run the command after then;
2. If the receipt is false, execute the command after else;

It is recommended that the writing format in the script be:
If CONDITION; then
STATEMENT
..
Else
STATEMENT
..
Fi

Or
If CONDITION;
Then
STATEMENT
..
Else
STATEMENT
..
Fi

Multi-branch structure of the if statement: (this is not recommended. It is too troublesome. We can use the following method to solve one or more nested statements)
If command; then Command; [elif command; then Command;]... [else command;] fi

Note: whether the command after then or else will be executed depends on the return value of the execution status of the command after if or the return value of the command after elif;
1. first, judge whether the return value of the command after if is true. if it is true, execute the statement after then. if it is false, continue to judge the return value of the execution status of the command after the first elif;
2. if the return value of the execution status of the command after the first elif statement is true, the command after the then in the first elif statement is executed. Otherwise, the return value of the command execution status after the second elif statement is determined;
3. similarly, it determines whether the return value of the command execution status after each elif is true. if the return value of the command execution status after all the if and elif is false, the statement following else is executed;

It is recommended that the writing format in the script be:
If CONDITION; then
STATEMENT
..
Elif CONDITION2; then
STATEMENT
..
Else; then
STATEMENT
..
Fi

Or
If CONDITION;
Then
STATEMENT
..
Elif CONDITION2; then
STATEMENT
..
Else
STATEMENT
..
Fi

Note: The multi-branch structure of if is rarely used. In some cases, you can use a nested single-branch or dual-branch if structure to replace the multi-branch structure of if;

Nested if structure:
If CONTITIONG1; then
If CONTITIONG2; then
If CONTITIONG3; then
STATEMENT
..
Else
STATEMENT
Fi
Else
STATEMENT
Fi
Else
STATEMENT
Fi

A good loop structure must include two important links;
1. Conditions for entering the loop:
The cycle starts only when the requirements are met or the conditions are met;

2. Conditions for exiting the loop:
When a certain requirement or condition is met, the execution of the cycle needs to be ended or terminated;

For Loop:
1. traverse the loop of the list:
Execute commands for each member in the list.
For name [in words...]; do command; done

Recommended format for writing in the script:
For VAR_NAME in LIST; do
Loop body
Done
Or
For VAR_NAME in LIST
Do
Loop body
Done

Note:
VAR_NAME: name of any specified variable. The value of the variable is the elements retrieved from the LIST traversal;
LIST: the LIST to be traversed by the for loop. You can generate a LIST in the following ways;
1. The list is provided directly;
2. Pure integer list;
1) curly braces:
{FIRSTNUM... LASTNUM}
{FIRST, SECOND, THIRD,..., LAST}
2) seq command
Seq [OPTION]... LAST
Seq [OPTION]... FIRST LAST
Seq [OPTION]... FIRST INCREMENT LAST
3. curly braces:
{FIRST .. LAST}
4. Command Execution result:
Ls/etc
5. GLOBBING wildcard
6. Values of some special variables:
$ *, $ @
Loop body:
In general, the loop body should be able to use the command or command combination of the value of the VAR_NAME variable; If the command in the loop body does not use the value of the VAR_NAME variable, the number of elements in the list, the number of times of the for loop;

1. The condition for entering the loop. The LIST contains elements not fully obtained;
2. Exit the loop condition. The elements in the LIST are exhausted;
3. for loops have almost no endless loops;
4. During the execution of the loop, the entire LIST needs to be loaded into the memory. For a large list, a large amount of memory and CPU resources may be consumed;

Simple example (Vim edit content)

1. Pass a string to the script. The script treats the string as the user name. If the user does not exist, add it and set the same password as the user name.

#! /Bin/bash
#
If [$ #-ne 1]; then
Echo "please input one name charast"
Exit 6;
Fi
If id $1 &>/dev/null; then
Echo "This user already exists"
Else
Useradd $1 &>/dev/null
Echo $1 | passwd -- stdin $1 &>/dev/null
Echo "This user creat and password is username"
Fi

2. pass the path of two text files to the script as its parameter. If a file does not exist, end the script execution and report the error message. If both files exist, compare the two files that have more lines, and return the file name with more lines.

#! /Bin/bash
#
Read-p "Please input two files:" FILE1 FILE2
If! Cat $ FILE1 &>/dev/null; then
Echo "please enter the first true path file"
Exit 5
If! Cat $ FILE2 &>/dev/null; then
Echo "please enter the second true path file"
Exit 5
Fi
Fi
LINE1 = $ (cat $ FILE1 | wc-l)
LINE2 = $ (cat $ FILE2 | wc-l)
If [$ LINE1-ne $ LINE2]; then
If [$ LINE1-gt $ LINE2]; then
Echo "$ FILE1"
Else
Echo "$ FILE2"
Fi
Else
Echo "$ FILE1 and $ FILE2 are generally long"
Fi
Unset FILE1 FILE2 LINE1 LINE2

3. Use the RANDOM variable to randomly generate ten numbers, display these ten numbers, and display the maximum and minimum values.

#! /Bin/bash
#
Touch/tmp/math.txt
For I in $ (seq 1 10); do
J = $ RANDOM
Echo "$ J"
Echo "$ J">/tmp/math.txt
Done
K = $ (sort-n/tmp/math.txt | head-1)
L = $ (sort-n/tmp/math.txt | tail-1)
Echo "laster $ L; leaster $ K"
Rm-rf/tmp/math.txt
Exit 5

4. pass a number to the script as the total number of rows, and print the isosceles triangle and diamond at the top and down of the smallest acute angle.

#! /Bin/bash
#
Read-p "enter one number:" INT
If [[$ INT = ~ [^ [: Digit:]; then
Echo "please enter the number"
Exit 5
Fi
Echo "zheng sanjiao"
For I in $ (seq $ INT); do
For J in $ (seq $ [INT-I]); do
Echo-n ""
Done
For K in $ (seq $[2 * I-1]); do
Echo-n "*"
Done
Echo
Done
Echo "dao sanjiao"
For M in $ (seq $ INT); do
For B in $ (seq $ [M-1]); do
Echo-n ""
Done
For N in $ (seq $[2 * (INT-M) + 1]); do
Echo-n "*"
Done
Echo
Done
Echo "lingxing"
If [$ [INT % 2]-ne 0]; then
INT2 = $ [(INT + 1)/2]
For Q in $ (seq $ INT2); do
For W in $ (seq $ [INT2-Q]); do
Echo-n ""
Done
For E in $ (seq $[2 * Q-1]); do
Echo-n "*"
Done
Echo
Done
For R in $ (seq $ [INT2-1]); do
For T in $ (seq $ [R]); do
Echo-n ""
Done
For Y in $ (seq $[2 * (INT2-R)-1]); do
Echo-n "*"
Done
Echo
Done
Exit 7
Else
Echo "qing shuru jishu> 3"
Fi

5. Print the sequence and the 9-9 multiplication table respectively.
The sequential 9-9 multiplication table is a normal 9-9 multiplication table;
The first row of the rotated 9-9 multiplication table is 1x1 = 1 1x2 = 2 1x3 = 3 1x4 = 4... 1 × 9 = 9; the second line is 2 × 2 = 4 2 × 3 = 6 2 × 4 = 8... 2 × 9 = 18 ;... the ninth line is 9 × 9 = 81;

#! /Bin/bash
#
For I in $ (seq 1 9); do
For J in $ (seq 1 $ I); do
Echo-ne "$ I × $ J = $ [I * J] \ t"
Done
Echo
Done
For M in $ (seq 1 9); do
For N in $ (seq $ M 9); do
Echo-ne "$ M × $ N = $ [N * M] \ t"
Done
Echo
Done

This article permanently updates link: https://www.bkjia.com/Linux/2018-03/151445.htm

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.