Table of Contents
A basic example" >A basic example
Compare numbers" >Compare numbers
Sample test" >Sample test
比较文本" >比较文本
比较文件" >比较文件
比较多个条件" >比较多个条件
排除 test 关键字" >排除 test 关键字
总结" >总结
Home System Tutorial LINUX How to use the powerful Linux test command in a Bash script

How to use the powerful Linux test command in a Bash script

Feb 09, 2024 pm 04:40 PM
linux linux tutorial linux system linux command shell script Getting started with linux linux learning

Linux’s test command is a built-in Shell command, used to check whether a certain condition is true. test is often used with if statements, and most if statements rely on test. It can compare one element to another, but is more commonly used in BASH shell scripts as part of conditional statements that control logic and program flow.

The test command has many options and can detect values, strings and files.

如何在 Bash 脚本中使用强大的 Linux test 命令

A basic example

Try these commands in a terminal window.

linuxmi@linuxmi /home/linuxmi/www.linuxmi.com                                   
⚡ test 1 -eq 2 && echo "yes" || echo "no"
no

linuxmi@linuxmi /home/linuxmi/www.linuxmi.com                                   
⚡ test 1 -eq 1 && echo "yes" || echo "no"
yes
Copy after login

The above command is broken down as follows:

    • test: Command to perform comparison
    • 1: The first element you want to compare. In this example, it's the number 1, but it can be any number or a string within quotes.
    • eq: Comparison method. In this case, you are testing whether one value is equal to another value.
    • 2: The element to which you want to compare the first element. In this example, it's the number 2.
    • **&&**: Linux shortcut for chaining commands together in sequence. The output of the test chain is passed to subsequent commands. A double ampersand is executed when the previous command's exit status is 0, which is a fancy way of indicating that the command did not fail.
    • echo “yes”: Command to run when comparison is successful. In this case, all we're doing is asking the echo command to print the word "yes" to standard output, but you can run any command here that will be executed if the test turns out to be true.
    • || : In a way, the opposite of &&; A double pipe will only execute if the command before it fails (exit status is not 0).
    • **echo "no"**: The command to run when the comparison does not match.

Tip: Running from a shell prompt, test* does not return a value to standard output, it only returns the exit status code. That's why you need to chain the echo command. *

如何在 Bash 脚本中使用强大的 Linux test 命令

Essentially the same, this command compares 1 with 2, if they match, execute the echo "yes" statement and display "yes", if they do not match, execute the echo "no" statement, Display "no".

Compare numbers

If you want to compare elements that resolve to numbers, you can use the following comparison operators:

  • -eq: Value 1 is equal to value 2
  • -ge : Value 1 is greater than or equal to value 2
  • -gt : Value 1 is greater than value 2
  • -le : Value 1 is less than or equal to value 2
  • -lt : Value 1 is less than value 2
  • -ne : Value 1 is not equal to value 2

Sample test

test 1 -eq 2 && echo "yes" || echo "no"
Copy after login

(displays "no" on the screen because 1 does not equal 2)

test 1 -ge 2 && echo "yes" || echo "no"
Copy after login

(displays "no" on the screen because 1 is not greater than or equal to 2)

test 1 -gt 2 && echo "yes" || echo "no"
Copy after login

(displays "no" on the screen because 1 is not greater than 2)

如何在 Bash 脚本中使用强大的 Linux test 命令
test 1 -le 2 && echo "yes" || echo "no"
Copy after login

(display "yes" on the screen because 1 is less than or equal to 2)

test 1 -lt 2 && echo "yes" || echo "no"
Copy after login

(display "yes" on the screen because 1 is less than or equal to 2)

test 1 -ne 2 && echo "yes" || echo "no"
Copy after login

(在屏幕上显示“yes”,因为 1 不等于 2)

如何在 Bash 脚本中使用强大的 Linux test 命令

比较文本

比较解析为字符串的元素时,请使用以下比较运算符:

  • **=**:字符串 1 匹配字符串 2
  • != : 字符串 1 与字符串 2 不匹配
  • -n:字符串长度大于0
  • -z:字符串长度等于 0

例子

test "string1" = "string2" && echo "yes" || echo "no"
Copy after login

(在屏幕上显示“no”,因为“string1”不等于“string2”)

test "string1" != "string2" && echo "yes" || echo "no"
Copy after login

(在屏幕上显示“yes”,因为“string1”不等于“string2”)

test -n "string1" && echo "yes" || echo "no"
Copy after login

(在屏幕上显示“yes”,因为“string1”的字符串长度大于零)

test -z "string1" && echo "yes" || echo "no"
Copy after login

(在屏幕上显示“no”,因为“string1”的字符串长度大于零)

如何在 Bash 脚本中使用强大的 Linux test 命令

比较文件

比较文件时,请使用以下比较运算符:

  • -ef:文件具有相同的设备和 inode 编号(它们是同一个文件)
  • -nt : 第一个文件比第二个文件新
  • -ot:第一个文件比第二个文件旧
  • -b:文件存在并且是块特殊的
  • -c:文件存在并且是字符特殊的
  • -d:文件存在并且是目录
  • -e : 文件存在
  • -f : 文件存在并且是普通文件
  • -g:文件存在并具有指定的组号
  • -G : 文件存在且属于用户组
  • -h或**-L**:文件存在并且是符号链接
  • -k:文件存在并且设置了粘性位
  • -O : 文件存在你是所有者
  • -p:文件存在并且是命名管道
  • -r:文件存在且可读
  • -s:文件存在且大小大于零
  • -S : 文件存在并且是一个socket
  • -t :在终端上打开文件描述符
  • -u:文件存在并且设置了 set-user-id 位
  • -w:文件存在且可写
  • -x:文件存在且可执行

例子

⚡ test linuxmi -nt linux && echo "yes"
Copy after login
如何在 Bash 脚本中使用强大的 Linux test 命令

(如果 linuxmi 比 linux 新,则显示“yes”字样,如上图

⚡ test -e /home/linuxmi/linuxmi && echo "yes"
Copy after login
如何在 Bash 脚本中使用强大的 Linux test 命令

(如果 linuxmi 存在,将显示“yes”)

test -O /home/linuxmi/linuxmi && echo "yes"
Copy after login
如何在 Bash 脚本中使用强大的 Linux test 命令

(如果您拥有 file1,则显示“yes”字样”)

块特殊:文件是块设备,这意味着数据以字节块的形式读取。这些通常是设备文件,例如硬盘驱动器。

特殊字符:文件在您写入时立即执行,通常是串行端口等设备

比较多个条件

到目前为止,一切都在将一件事与另一件事进行比较,但是如果您想比较两个条件怎么办?

例如,如果一只动物有四条腿并且会发出“哞哞”的声音,它可能是一头奶牛。简单地检查四只腿并不能保证你有一头牛,但检查它发出的声音肯定可以。

要同时测试这两个条件,请使用以下语句:

test 4 -eq 4 -a "moo" = "moo" && echo "it is a cow" || echo "it is not a cow"
Copy after login
这里的关键部分是-a标志,它代表and。
Copy after login

有一种更好和更常用的方法来执行相同的测试,如下所示:

test 4 -eq 4 && test "moo" = "moo" && echo "it is a cow" || echo "it is not a cow"
Copy after login

test 命令的分支很重要。如果第一个测试 (4 = 4) 失败,则 *test* 命令以非零退出代码终止。因此,我们跳转到双管道符号并且“it is not a cow”打印到标准输出。但是,如果第一个测试成功并因此 test 导致退出代码0,那么我们跳转到第一个双与号(&&)。下一条语句是另一个测试条件!

如果第二次 test 失败,我们再次跳到双管并从那里继续。然而,如果第二个 test 成功,我们跳转到第二个双& 语句,在这个例子中,它只是将“it is a cow”回显到标准输出,然后终止返回到 shell 提示符。

另一个测试比较两个语句,如果其中一个为真,则输出一个字符串。例如,要检查是否存在名为“linuxmi.txt”的文件或名为“linuxmi.py”的文件,可以使用以下命令:

这里的关键部分是**-o**代表or

test -e linuxmi.txt -o -e linuxmi.py && echo "linuxmi exists" || echo "linuxmi does not exist"
Copy after login

有一种更好和更常用的方法来执行相同的测试,如下所示:

test -e linuxmi.txt || test -e linuxmi.py && echo "linuxmi exists" || echo "linuxmi does not exist"
Copy after login

排除 test 关键字

您实际上不需要使用单词test来执行比较。您所要做的就是将语句括在方括号中,如下所示:

⚡ [ -e linux.py ] && echo "linux.py
exists" || echo "file1 does not exist"linux.py exists
Copy after login

[and**]基本上与****test含义 相同。**

如何在 Bash 脚本中使用强大的 Linux test 命令

现在您知道这一点,您可以改进比较多个条件,如下所示:

[ 4 -eq 4 ] && [ "moo" = "moo" ] && echo "it is a cow" || echo "it is not a cow"

[ -e linuxmi.py ] || [ -e linuxmi.txt ] && echo "linuxmi exists" || echo "linuxmi does not exist"
Copy after login
如何在 Bash 脚本中使用强大的 Linux test 命令

总结

test 命令在脚本中更有用,因为您可以对照另一个变量测试一个变量的值并控制程序流程。在命令行上,使用它来测试文件是否存在。

The above is the detailed content of How to use the powerful Linux test command in a Bash script. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use docker desktop How to use docker desktop Apr 15, 2025 am 11:45 AM

How to use Docker Desktop? Docker Desktop is a tool for running Docker containers on local machines. The steps to use include: 1. Install Docker Desktop; 2. Start Docker Desktop; 3. Create Docker image (using Dockerfile); 4. Build Docker image (using docker build); 5. Run Docker container (using docker run).

How to view the docker process How to view the docker process Apr 15, 2025 am 11:48 AM

Docker process viewing method: 1. Docker CLI command: docker ps; 2. Systemd CLI command: systemctl status docker; 3. Docker Compose CLI command: docker-compose ps; 4. Process Explorer (Windows); 5. /proc directory (Linux).

Difference between centos and ubuntu Difference between centos and ubuntu Apr 14, 2025 pm 09:09 PM

The key differences between CentOS and Ubuntu are: origin (CentOS originates from Red Hat, for enterprises; Ubuntu originates from Debian, for individuals), package management (CentOS uses yum, focusing on stability; Ubuntu uses apt, for high update frequency), support cycle (CentOS provides 10 years of support, Ubuntu provides 5 years of LTS support), community support (CentOS focuses on stability, Ubuntu provides a wide range of tutorials and documents), uses (CentOS is biased towards servers, Ubuntu is suitable for servers and desktops), other differences include installation simplicity (CentOS is thin)

What to do if the docker image fails What to do if the docker image fails Apr 15, 2025 am 11:21 AM

Troubleshooting steps for failed Docker image build: Check Dockerfile syntax and dependency version. Check if the build context contains the required source code and dependencies. View the build log for error details. Use the --target option to build a hierarchical phase to identify failure points. Make sure to use the latest version of Docker engine. Build the image with --t [image-name]:debug mode to debug the problem. Check disk space and make sure it is sufficient. Disable SELinux to prevent interference with the build process. Ask community platforms for help, provide Dockerfiles and build log descriptions for more specific suggestions.

What computer configuration is required for vscode What computer configuration is required for vscode Apr 15, 2025 pm 09:48 PM

VS Code system requirements: Operating system: Windows 10 and above, macOS 10.12 and above, Linux distribution processor: minimum 1.6 GHz, recommended 2.0 GHz and above memory: minimum 512 MB, recommended 4 GB and above storage space: minimum 250 MB, recommended 1 GB and above other requirements: stable network connection, Xorg/Wayland (Linux)

vscode cannot install extension vscode cannot install extension Apr 15, 2025 pm 07:18 PM

The reasons for the installation of VS Code extensions may be: network instability, insufficient permissions, system compatibility issues, VS Code version is too old, antivirus software or firewall interference. By checking network connections, permissions, log files, updating VS Code, disabling security software, and restarting VS Code or computers, you can gradually troubleshoot and resolve issues.

Detailed explanation of docker principle Detailed explanation of docker principle Apr 14, 2025 pm 11:57 PM

Docker uses Linux kernel features to provide an efficient and isolated application running environment. Its working principle is as follows: 1. The mirror is used as a read-only template, which contains everything you need to run the application; 2. The Union File System (UnionFS) stacks multiple file systems, only storing the differences, saving space and speeding up; 3. The daemon manages the mirrors and containers, and the client uses them for interaction; 4. Namespaces and cgroups implement container isolation and resource limitations; 5. Multiple network modes support container interconnection. Only by understanding these core concepts can you better utilize Docker.

What is vscode What is vscode for? What is vscode What is vscode for? Apr 15, 2025 pm 06:45 PM

VS Code is the full name Visual Studio Code, which is a free and open source cross-platform code editor and development environment developed by Microsoft. It supports a wide range of programming languages ​​and provides syntax highlighting, code automatic completion, code snippets and smart prompts to improve development efficiency. Through a rich extension ecosystem, users can add extensions to specific needs and languages, such as debuggers, code formatting tools, and Git integrations. VS Code also includes an intuitive debugger that helps quickly find and resolve bugs in your code.

See all articles