Linux Bash Shell Learning (15th): variable type and integer calculation

Source: Internet
Author: User

This article is Chapter 6 of "Learning the bash Shell" 3rd Edition, Command-Line Options and Typed varilables, but we will not limit it to this.

Previously, the variables we involved were basically strings and integers, for example, $ # Of the number of parameters #. We can use declare to define the attributes of variables.

Variable Type Definition

Declare-

Name

: Array.

Declare-f

Name

: Indicates the name of a function.

Declare-F

Name

: Same as above, but only the function name is displayed. This is not clear from the above specific differences, but the two are rarely used. Ignore them first.

Declare-I

Name

: Represents an integer

Declare-r

Name

: Indicates read-only. You cannot use unset. You can also use Read-Only variablesReadonly

Name

Is equivalent to declare-r.Name

. Readonly can include three options:-f indicates the name of a function,-p indicates that all readonly names are printed, and-a indicates that this is a read-only array.

Declare-x

Name

: Same as export, that is, it not only plays a role in the current environment, but also in the external shell environment.

Integer Operation

We can use declare-I to define integer variables. In the last learning, $ ($ OPTIND-1) was used for calculation $ ((...)) Is used for integer calculation. At $ ((...)) In, we do not need to add $ to the variable to represent its value, nor do we need to declare it as an integer in advance. It can also be effectively calculated under double quotation marks. The following is an example:

# Declare-I aa = 13

Aa = 13

Echo '$ (aa-3)' = $(aa-3 ))

Echo '$ ($ aa-3)' = $ ($ aa-3 ))

# Date: date + % j indicates the day of the year, and $ (command) indicates the result.

Echo "Only $ (((365-$ (date + % j)/7

) Weeks until the New Year"

We do not need to declare that aa is an integer because $ ((...)) It indicates that it is an integer operation, and the character is automatically changed to an integer.

The operation type is the same as that in C. The format of $ (x + = 2) is also supported, including the following operations. In the following example, we reference the above aa = 13.

  • ++: $ (Aa ++) is 13, and the value of aa is 14. If you use $ ($ aa ++), an error is returned, the meaning of 13 ++ cannot be parsed. Therefore, for the sake of conciseness and no errors, $ is not added to the formula. If $ (+ aa) is set to 14, assign the value of aa to 14, which is the same as that of C.
  • --: $ (Aa --) is 13, aa is assigned to 12, $ (-- aa) is 12, and aa is assigned to 12.
  • +
  • -
  • *
  • /
  • %: Remainder: $ (aa % 5) = 3
  • **: This is not available in C. It indicates Exponentiation, that is, power. For example, in the above example, $ ($ aa ** 3) is equivalent to 13*13*13 = 2197.
  • <
  • >
  • &
  • |
  • ~
  • !
  • ^

It also supports logical operations, including<,>, <=, >=, = ,! =, &, |,

These are the same as those in C. For example, $ (3> 1) is 1. This is really different from running return 0. One is the result of the logical operation, and the other is the exit status. For example, the preceding $ (3> 1) is 1, the logical calculation result is 1, and the execution result's exit status is 0. These two concepts need to be differentiated.

We are in http://blog.csdn.net/flowingflying/archive/2009/12/22/5069646.aspx

The same [... ] Condition determination method. Here, the >,<,= symbol is used to determine the string, indicating that it is used to compare numbers. In [... ], If you compare numbers, you need to use-Lt,-gt,-le,-ge,-eq,-ne

. Use [... ], For example, if [3-gt 20]; then, the condition is not true, but [3> 20], it is true because the string is compared at the moment. So this is very confusing. If the expression is complex, for example, [/(3-gt 2/) |/(4-le 1/)] is not very easy to read. We need to emphasize that in if [condition]; then, shell indicates that the function or command is successful if it is 0. Therefore, if is used to determine whether it is 0, this is different from the mathematical logic operation of $. For the above example, you can useIf [$ (3> 2) & (4 <= 1) = 1]

, The previous (3> 2) & (4 <= 1) operation structure is 1, and then compare it with [str1 = str2] to determine whether it is true. It is still very troublesome to write and useIf (3> 2) & (4 <= 1 )))

, That is((...))

.

For the assignment of mathematical operations, the use of $ (...) is sometimes more complex, you can use let, the format is as follows:

LetIntvar

=Expression

Let indicates that expression is a mathematical operation. You do not need to use $ () for further demonstration. This assignment method is much simpler. There is no space before and after the equal sign, and there is no space in the expression. If there is a space that must be caused by quotation marks, it can be single quotation marks or double quotation marks, let x = 1 + 4; let x = '1 + 4'; let x = "1 + 4". These three values are also assigned to x as 5. The following is an example to obtain the space occupied by a specified directory:

Function test1

{

Echo "test1 $ {*}"

For dir in $ {*:-.}; do

If [-e $ dir]; then

# Du-estimate file space usage, number of returned Blocks

Result = $ (du-s $ dir | cut-f 1)

Let total = $ result * 1024

Echo-n "Total for $ dir = $ total bytes"

If [$ total-ge 1048576]; then

Echo "($ (Total/1048576) Mb

)"

Elif [$ total-ge 1024]; then

Echo "($ (Total/1024) Kb

)"

Fi

Fi

Done

}

The following is a large example of pushd and popd which has been used in this book. Some functions are enhanced. When pushnd + n, move the nth element to the top and enter the directory. If there is no parameter, swap the two most recent elements and enter the top directory after the switch, otherwise, the original pushd processing method will be processed. If popnd + n is used, the nth element is deleted from the stack, and other elements are processed in the same way as those in popd.

# Obtain the nth parameter in the stack, calculate it from 0, store the first N in stackfront, and store the last n in the stack.

Function getNdirs

{

Echo getndirs $ @

Stackfront =''

Let COUNT = 0

# The number of times can be controlled like C through mathematical calculation and numerical determination. Because for is used for list elements, the first n entries are stored in stackfront after the while and loop are used, if n is included, the stack stores the following elements. The target stores the nth element.

While [$ count-le $1] & [-n "$ stack"]; do

# Target is the top-level entry in the stack, containing Spaces

Target =$ {stack % $ {stack #*}}

# Store the top entry behind stackfront

Stackfront = "$ stackfront $ target"

# Stack is the value after obtaining the top entry

Stack =$ {stack # $ target}

Let COUNT = count + 1

Done

# Remove the nth element from stackfont again, then stackfont stores the elements before n

Stackfront =$ {stackfront % $ target}

}

# When pushnd + N, move the nth element to the top and enter the directory. If there is no parameter, swap the two most recent elements, and enter the top directory after the switch, otherwise the anpushd processing method will be processed.

Function pushnd

{

Echo

Echo pushnd $ @

# Check if pushnd + N is used, you need to move the n elements to the top of the list.

If [$ (echo $1 | grep '^ + [0-9] [0-9] * $')]; then

# Remove + FROM parameter 1 and obtain n

Let num =$ {1 # +}

GetNdirs $ num

Stack = "$ target $ stackfront $ stack"

CD $ Target

Elif [-z "$1"]; then

# Case of pushnd without ARGs; Swap top two directories

Firstdir =$ {stack % *}

Stack =$ {stack #*}

Seconddir =$ {stack % *}

Stack =$ {stack #*}

Stack = "$ seconddir $ firstdir $ stack"

Cd $ seconddir

 Else

# Normal case of pushd dirname

Dirname = $1

#-A is equivalent &&

If [/(-d $ dirname/)-a/(-x $ dirname/)]; then

Stack = "$ dirname $ {stack:-$ PWD ""}"

Cd $ dirname

Fi

Fi

Echo "stack = $ stack"

Echo "directory = $ PWD"

}

# If popnd + n is used, the nth element is deleted from the stack.

Function popnd

{

Echo

Echo popnd $ @

If [$ (echo $1 | grep '^ + [0-9] [0-9] * $')]; then

# Case of popd + n: delete n-th directory from stack

Let num =$ {1 # +}

GetNdirs $ num

Stack = "$ stackfront $ stack"

# Cd $ {stack % *}

Else

If [-n "$ stack"]; then

Stack =$ {stack #*}

If [-n "$ stack"]; then

Cd $ {stack % *}

Else

Echo "stack becomes empty ."

Fi

Else

Echo "stack already empty ."

Fi

Fi

Echo "stack = $ stack"

Echo "directory = $ PWD"

}

Pushnd/home

Pushnd/etc

Pushnd/home/wei/mywork

Pushnd + 3

Pushnd

Pushnd + 1

Popnd + 3

Popnd

Popnd

Popnd

For application

We want to use for, C, or JAVA in the following format:

For ((Initialisation

;Ending condition

;Update

))

Do

Statements

...

Done


If you useFor ((;;))

Ze indicates an infinite loop. In statements, you can use break to exit the loop. The following is an example of a 9-9 multiplication table:

For (I = 1; I <= 9; I ++ ))

Do

For (j = 1; j <= 9; j ++ ))

Do

Echo-ne "$ (j * I)/t"

Done

Echo

Done

Related Links: My articles on Linux operations

 

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.