← 返回命令列表

Linux command

test 命令

文件

涉及管道、覆盖或删除,执行前请先确认路径和参数。

常用示例

Check if a file exists

test -e [path/to/file] && echo "exists"

Check if file is a directory

test -d [path/to/dir] && echo "is directory"

Check if file is readable

test -r [path/to/file] && echo "readable"

Compare strings for equality

test "[string1]" = "[string2]"

Check if string is non-empty

test -n "[string]"

Compare integers

test [5] -gt [3] && echo "greater"

Combine conditions with AND

test -f [file] -a -r [file]

Combine conditions with OR

test -f [file1] -o -f [file2]

说明

test evaluates conditional expressions, returning exit status 0 (true) or 1 (false). It is commonly used in shell scripts for decision-making in if statements and loops. The command can also be invoked as with a closing required as the last argument. This bracket syntax is more readable in conditionals: if -f file ; then. Modern shells also provide [[ which offers additional features like pattern matching and safer string handling, but is not POSIX-compliant.

FAQ

What is the test command used for?

test evaluates conditional expressions, returning exit status 0 (true) or 1 (false). It is commonly used in shell scripts for decision-making in if statements and loops. The command can also be invoked as with a closing required as the last argument. This bracket syntax is more readable in conditionals: if -f file ; then. Modern shells also provide [[ which offers additional features like pattern matching and safer string handling, but is not POSIX-compliant.

How do I run a basic test example?

Run `test -e [path/to/file] && echo "exists"` in a terminal, then adjust file names, paths, flags, or remote targets for your system.

Where can I find more test examples?

This page includes 8 examples for test, plus related commands for nearby Linux tasks.