在Linux脚本中,test
命令通常用于进行条件测试
#!/bin/bash
num1=10
num2=20
if test $num1 -lt $num2; then
echo "Number 1 is less than Number 2"
else
echo "Number 1 is not less than Number 2"
fi
#!/bin/bash
str1="hello"
str2="world"
if test "$str1" != "$str2"; then
echo "String 1 is not equal to String 2"
else
echo "String 1 is equal to String 2"
fi
#!/bin/bash
file="/path/to/your/file"
if test -e "$file"; then
echo "File exists"
else
echo "File does not exist"
fi
#!/bin/bash
num1=10
num2=20
if test $num1 -lt $num2; then
if test $num1 -eq $num2; then
echo "Number 1 is less than and equal to Number 2"
else
echo "Number 1 is less than Number 2"
fi
else
if test $num1 -eq $num2; then
echo "Number 1 is greater than and equal to Number 2"
else
echo "Number 1 is greater than Number 2"
fi
fi
注意:在脚本中使用 test
命令时,建议使用双方括号 [[ ]]
进行条件测试,因为它提供了更强大的功能和更好的可读性。例如:
#!/bin/bash
num1=10
num2=20
if [[ $num1 -lt $num2 ]]; then
echo "Number 1 is less than Number 2"
else
echo "Number 1 is not less than Number 2"
fi