search
HomeSystem TutorialLINUXHow 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
linuxlinux tutoriallinux systemlinux commandshell scriptGetting started with linuxlinux 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

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"

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

test 1 -ge 2 && echo "yes" || echo "no"

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

test 1 -gt 2 && echo "yes" || echo "no"

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

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

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

test 1 -lt 2 && echo "yes" || echo "no"

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

test 1 -ne 2 && echo "yes" || echo "no"

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

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

比较文本

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

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

例子

test "string1" = "string2" && echo "yes" || echo "no"

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

test "string1" != "string2" && echo "yes" || echo "no"

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

test -n "string1" && echo "yes" || echo "no"

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

test -z "string1" && echo "yes" || echo "no"

(在屏幕上显示“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"
如何在 Bash 脚本中使用强大的 Linux test 命令

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

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

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

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

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

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

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

比较多个条件

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

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

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

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

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

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

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"

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

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

排除 test 关键字

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

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

[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"
如何在 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
This article is reproduced at:良许Linux教程网. If there is any infringement, please contact admin@php.cn delete
What are the main tasks of a Linux system administrator?What are the main tasks of a Linux system administrator?Apr 19, 2025 am 12:23 AM

The main tasks of Linux system administrators include system monitoring and performance tuning, user management, software package management, security management and backup, troubleshooting and resolution, performance optimization and best practices. 1. Use top, htop and other tools to monitor system performance and tune it. 2. Manage user accounts and permissions through useradd commands and other commands. 3. Use apt and yum to manage software packages to ensure system updates and security. 4. Configure a firewall, monitor logs, and perform data backup to ensure system security. 5. Troubleshoot and resolve through log analysis and tool use. 6. Optimize kernel parameters and application configuration, and follow best practices to improve system performance and stability.

Is it hard to learn Linux?Is it hard to learn Linux?Apr 18, 2025 am 12:23 AM

Learning Linux is not difficult. 1.Linux is an open source operating system based on Unix and is widely used in servers, embedded systems and personal computers. 2. Understanding file system and permission management is the key. The file system is hierarchical, and permissions include reading, writing and execution. 3. Package management systems such as apt and dnf make software management convenient. 4. Process management is implemented through ps and top commands. 5. Start learning from basic commands such as mkdir, cd, touch and nano, and then try advanced usage such as shell scripts and text processing. 6. Common errors such as permission problems can be solved through sudo and chmod. 7. Performance optimization suggestions include using htop to monitor resources, cleaning unnecessary files, and using sy

What is the salary of Linux administrator?What is the salary of Linux administrator?Apr 17, 2025 am 12:24 AM

The average annual salary of Linux administrators is $75,000 to $95,000 in the United States and €40,000 to €60,000 in Europe. To increase salary, you can: 1. Continuously learn new technologies, such as cloud computing and container technology; 2. Accumulate project experience and establish Portfolio; 3. Establish a professional network and expand your network.

What is the main purpose of Linux?What is the main purpose of Linux?Apr 16, 2025 am 12:19 AM

The main uses of Linux include: 1. Server operating system, 2. Embedded system, 3. Desktop operating system, 4. Development and testing environment. Linux excels in these areas, providing stability, security and efficient development tools.

Does the internet run on Linux?Does the internet run on Linux?Apr 14, 2025 am 12:03 AM

The Internet does not rely on a single operating system, but Linux plays an important role in it. Linux is widely used in servers and network devices and is popular for its stability, security and scalability.

What are Linux operations?What are Linux operations?Apr 13, 2025 am 12:20 AM

The core of the Linux operating system is its command line interface, which can perform various operations through the command line. 1. File and directory operations use ls, cd, mkdir, rm and other commands to manage files and directories. 2. User and permission management ensures system security and resource allocation through useradd, passwd, chmod and other commands. 3. Process management uses ps, kill and other commands to monitor and control system processes. 4. Network operations include ping, ifconfig, ssh and other commands to configure and manage network connections. 5. System monitoring and maintenance use commands such as top, df, du to understand the system's operating status and resource usage.

Boost Productivity with Custom Command Shortcuts Using Linux AliasesBoost Productivity with Custom Command Shortcuts Using Linux AliasesApr 12, 2025 am 11:43 AM

Introduction Linux is a powerful operating system favored by developers, system administrators, and power users due to its flexibility and efficiency. However, frequently using long and complex commands can be tedious and er

What is Linux actually good for?What is Linux actually good for?Apr 12, 2025 am 12:20 AM

Linux is suitable for servers, development environments, and embedded systems. 1. As a server operating system, Linux is stable and efficient, and is often used to deploy high-concurrency applications. 2. As a development environment, Linux provides efficient command line tools and package management systems to improve development efficiency. 3. In embedded systems, Linux is lightweight and customizable, suitable for environments with limited resources.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software