Use of the Shell Foundation--test command

Source: Internet
Author: User

Test: For file type checking and variable comparison

A. Use:

1. Judging expressions

 

2. Judging the string

3. Judging integers

4. Judging documents

Test examples:

(1). Test

[Email protected] ~_~ day5]# cat test.sh

#!/bin/bash

A=$1

B=$2

if test $a-eq $b

Then

echo "A=b"

Else

echo "A!=b"

Fi

[[email protected] ~_~ day5]# sh test.sh 1 1

A=b

[[email protected] ~_~ day5]# sh test.sh 1 2

A!=b

---------------------------------------------

(2). []

[Email protected] ~_~ day5]# cat test.sh

#!/bin/bash

A=$1

B=$2

[$a = $b] && echo "A=b" | | echo "A!=b"

[[email protected] ~_~ day5]# sh test.sh 1 2

A!=b

[[email protected] ~_~ day5]# sh test.sh 1 1

A=b

-------------------------------------------------

(3). judgment file

[Email protected] ~_~ day5]# cat test2.sh

#!/bin/bash

[-F "$"]&& echo "$ is a file" | | echo "$ is not a file"

[Email protected] ~_~ day5]# sh test2.sh

Test2.sh is a file

Two. test,[], [[]] usage comparison

[] equivalent to test, both the shell gets the internal command, and [[]] is the shell to get the keyword, bash the expression in double brackets as a separate element, and return an exit status code, it is recommended to use [[]] as a conditional judgment statement, not easy to appear logic error. Also, [[]] supports pattern matching and regular expressions

(1). Syntax comparison

[[]]: if [[$a! = 1 && $a! = 2]]

[]: If [$a-ne 1] && [$a! = 2] or if [$a-ne 1-a $a! = 2]

(2). [[]] Support pattern matching

[Email protected] ~_~ day5]# cat test4.sh

#!/bin/bash

[["ABCD" = = A*d]]&& echo True | | Echo flase

["abcd" = = A*d]&& echo True | | Echo flase

[Email protected] ~_~ day5]# sh test4.sh

True

Flase

(3). [[]] supports regular expressions

[Email protected] ~_~ day5]# cat test5.sh

[["Hello" =~ ^h]]&& echo Ture | | Echo False

[Email protected] ~_~ day5]# sh test5.sh

Ture

Use of the Shell Foundation--test command

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.