Shell Test 命令学习笔记
简介
Test 命令是 Shell 中用于条件测试的内置命令之一。它可以测试一个特定的条件是否为真,并返回 0 或 1 的结果。
在 Shell 脚本中,test 命令通常被用于 if 语句、while 循环等结构中,用于判断条件是否成立。
基本语法
test 命令的基本语法如下:
Copy Codetest condition
其中,condition 是要测试的条件表达式。test 命令会对这个表达式进行求值,如果表达式为真,则返回 0,否则返回 1。
test 命令还有一种等效的写法,即使用方括号 [] 将条件表达式括起来:
Copy Code[ condition ]
使用方括号的写法与使用 test 命令的写法是等价的。
测试条件
test 命令可以测试的条件非常多,以下是一些常见的条件类型:
文件测试
条件 | 描述 |
---|---|
-e file | 测试文件或目录是否存在 |
-f file | 测试文件是否存在且为普通文件 |
-d file | 测试文件是否存在且为目录 |
-r file | 测试文件是否可读 |
-w file | 测试文件是否可写 |
-x file | 测试文件是否可执行 |
-s file | 测试文件是否存在且非空 |
例如,要测试文件 /etc/passwd 是否存在:
Copy Codeif [ -e /etc/passwd ]; then
echo "/etc/passwd exists."
fi
字符串测试
条件 | 描述 |
---|---|
-z string | 测试字符串是否为空 |
-n string | 测试字符串是否非空 |
string1 = string2 | 测试两个字符串是否相等 |
string1 != string2 | 测试两个字符串是否不相等 |
例如,要测试变量 $str 是否为空:
Copy Codeif [ -z "$str" ]; then
echo "The variable is empty."
fi
数值测试
条件 | 描述 |
---|---|
int1 -eq int2 | 测试两个整数是否相等 |
int1 -ne int2 | 测试两个整数是否不相等 |
int1 -gt int2 | 测试 int1 是否大于 int2 |
int1 -ge int2 | 测试 int1 是否大于等于 int2 |
int1 -lt int2 | 测试 int1 是否小于 int2 |
int1 -le int2 | 测试 int1 是否小于等于 int2 |
例如,要测试变量 $num 是否大于 10:
Copy Codeif [ "$num" -gt 10 ]; then
echo "The number is greater than 10."
fi
实例
以下是一个简单的 Shell 脚本示例,它会测试用户输入的字符串是否为 "hello",如果是,则输出 "Hello, world!",否则输出 "You are not friendly."
Copy Code#!/bin/bash
echo "Please enter a string: "
read str
if [ "$str" = "hello" ]; then
echo "Hello, world!"
else
echo "You are not friendly."
fi