English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Shell test Command

Der Befehl test in Shell wird verwendet, um zu überprüfen, ob eine Bedingung erfüllt ist. Er kann numerische, zeichenbasierte und Datei-Tests durchführen.

Numerischer Test

Parameter Description
-eq gleich ist wahr
-ne ungleich ist wahr
-gt größer ist wahr
-ge größer oder gleich ist wahr
-lt kleiner ist wahr
-le kleiner oder gleich ist wahr
num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'Zwei Zahlen sind gleich!'
else
    echo 'Zwei Zahlen sind ungleich!'
fi

Output Result:

Zwei Zahlen sind gleich!

Die [] im Code führen grundlegende arithmetische Operationen durch, wie z.B.:

#!/bin/bash
a=5
b=6
result=$[a+b] # Beachte, dass auf beiden Seiten des Gleichzeichens kein Leerzeichen sein darf
echo "result ist: $result"

Das Ergebnis ist:

result ist: 11

String-Test

Parameter Description
= gleich ist wahr
!== ungleich ist wahr
-z String Die Länge des Strings ist null, dann ist es wahr
-n String The length of the string is not zero, it is true
num1="ru1noob"
num2="w3codebox"
if test $num1 = $num2
then
    echo 'Two strings are equal!'
else
    echo 'Two strings are not equal!'
fi

Output Result:

Two strings are not equal!

File Test

Parameter Description
-e File name If the file exists, it is true
-r File name If the file exists and is readable, it is true
-w File name If the file exists and is writable, it is true
-x File name If the file exists and is executable, it is true
-s File name If the file exists and at least one character, it is true
-d File name If the file exists and is a directory, it is true
-f File name If the file exists and is a regular file, it is true
-c File name If the file exists and is a character special file, it is true
-b File name If the file exists and is a block special file, it is true
cd /bin
if test -e ./bash
then
    echo 'File already exists!'
else
    echo 'File does not exist!'
fi

Output Result:

File already exists!

In addition, Shell also provides with( -a )、或( -o )、非( ! ) three logical operators are used to connect test conditions, with their priority as: ! highest, -a Next, -o Lowest. For example:

cd /bin
if test -e ./notFile -o -e ./bash
then
    echo 'At least one file exists!'
else
    echo 'Two files do not exist'
fi

Output Result:

At least one file exists!