Linux test command and

Команда test

Предназначена для проверки типа файла и сравнения чисел и строк. Возвращает код возврата 0 (истина) или 1 (ложь) в зависимости от вычисления выражения. Выражения могут быть как унарными, так и бинарными.

Для сокращения кода сценария используют парный оператор [ как синоним test . Парный оператор требует пробела между скобками потому, что [ (скобка) является командой оболочки.

Проверка типа файла

  • -d file — истина, если file существует и является каталогом
  • -e file — истина, если file существует
  • -f file — истина, если file существует и является обычным файлом
  • -r file — истина, если file существует и доступен для чтения
  • -s file — истина, если file существует и имеет размер больше, чем ноль
  • -w file — истина, если file существует и доступен для записи
  • -x file — истина, если file существует и доступен для выполнения
  • -L file — истина, если file существует и является символьной ссылкой
  • file1 -nt file2 — истина, если file1 новее (дата модификации), чем file2
  • file1 -ot file2 — истина, если file1 старее, чем file2

Сравнение строк

  • -z string — истина, если длина string равна нулю
  • -n string — истина, если длина string не ноль
  • string1 = string2 — истина, если строки равны
  • string1 != string2 — истина, если строки не равны

Сравнение целых чисел

  • число1 -eq число2 — истина, если число1 равно число2
  • число1 -gt число2 — истина, если число1 больше число2
  • число1 -ge число2 — истина, если число1 больше или равно число2
  • число1 -lt число2 — истина, если число1 меньше число2
  • число1 -le число2 — истина, если число1 меньше или равно число2
  • число1 -ne число2 — истина, если число1 не равно число2

Операции AND и OR

  • expr1 -a expr2 — истина, если оба выражения expr1 и expr2 истина (операция AND)
  • expr1 -o expr2 — истина, если хотя бы одно из выражений expr1 или expr2 истина (операция OR)
  • ! expr — истина, если выражение expr ложно

В условном выражении команды test можно использовать круглые скобки, чтобы изменить порядок вычисления, но их нужно экранировать:

« [[…]] » — расширенный вариант от « […] », оболочка выполняет его как один элемент с кодом возврата. Внутри « [[…]] » разрешается выполнение операторов && , || которые приводят к ошибке в обычных скобках « […] ».

Источник

Linux test command

On Unix-like operating systems, the test command checks file types and compares values.

This page covers the GNU/Linux version of test.

For information about the test command in bash see our bash test command page.

Description

test is used as part of the conditional execution of shell commands.

test exits with the status determined by EXPRESSION. Placing the EXPRESSION between square brackets ([ and ]) is the same as testing the EXPRESSION with test. To see the exit status at the command prompt, echo the value «$?» A value of 0 means the expression evaluated as true, and a value of 1 means the expression evaluated as false.

Читайте также:  Как сделать чтобы компьютер сам включался windows 10

Syntax

Expressions

Expressions take the following forms:

( EXPRESSION ) EXPRESSION is true
! EXPRESSION EXPRESSION is false
EXPRESSION1 -a EXPRESSION2 both EXPRESSION1 and EXPRESSION2 are true
EXPRESSION1 -o EXPRESSION2 either EXPRESSION1 or EXPRESSION2 is true
-n STRING the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING the length of STRING is zero
STRING1 = STRING2 the strings are equal
STRING1 != STRING2 the strings are not equal
INTEGER1 -eq INTEGER2 INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2 INTEGER1 is greater than or equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is greater than INTEGER2
INTEGER1 -le INTEGER2 INTEGER1 is less than or equal to INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is less than INTEGER2
INTEGER1 -ne INTEGER2 INTEGER1 is not equal to INTEGER2
FILE1 -ef FILE2 FILE1 and FILE2 have the same device and inode numbers
FILE1 -nt FILE2 FILE1 is newer (modification date) than FILE2
FILE1 -ot FILE2 FILE1 is older than FILE2
-b FILE FILE exists and is block special
-c FILE FILE exists and is character special
-d FILE FILE exists and is a directory
-e FILE FILE exists
-f FILE FILE exists and is a regular file
-g FILE FILE exists and is set-group-ID
-G FILE FILE exists and is owned by the effective group ID
-h FILE FILE exists and is a symbolic link (same as -L)
-k FILE FILE exists and has its sticky bit set
-L FILE FILE exists and is a symbolic link (same as -h)
-O FILE FILE exists and is owned by the effective user ID
-p FILE FILE exists and is a named pipe
-r FILE FILE exists and read permission is granted
-s FILE FILE exists and has a size greater than zero
-S FILE FILE exists and is a socket
-t FD file descriptor FD is opened on a terminal
-u FILE FILE exists and its set-user-ID bit is set
-w FILE FILE exists and write permission is granted
-x FILE FILE exists and execute (or search) permission is granted

Except for -h and -L, all FILE-related tests dereference symbolic links. Beware that parentheses need to be escaped (e.g., by backslashes) for shells. INTEGER may also be -l STRING, which evaluates to the length of STRING.

NOTE: your shell may have its own version of test, which usually supersedes the version described here. Please refer to your shell’s documentation for details about the options it supports.

Examples

This command prints the text «Yes, that’s true.» because 100 is greater than 99.

This command prints the text «No.» because 100 is not less than 99.

This command prints «0» because the expression is true; the two strings are identical.

This command prints «1» because the expression is false; 5 does not equal 6.

Источник

Bash test builtin command

On Unix-like operating systems, test is a builtin command of the Bash shell that tests file attributes, and perform string and arithmetic comparisons.

Читайте также:  Ms get started windows 10 как исправить

Description

test provides no output, but returns an exit status of 0 for «true» (test successful) and 1 for «false» (test failed).

The test command is frequently used as part of a conditional expression. For instance, the following statement says, «If 4 is greater than 5, output yes, otherwise output no.»

The following statement says, «If 6 is greater than 5, output yes, otherwise output no.»

The test command may also be expressed with single brackets [ . ], as long as they are separated from all other arguments with whitespace. For example, the following statement checks that the system file /etc/passwd exists, and if not, outputs «uh-oh.»

Syntax

Shell options and variables:

Simple logic (test if values are null):

Numerical comparison (for integer values only; bash doesn’t do floating point math):

Options

The test builtin command takes the following options.

-a file Returns true if file exists. Does the same thing as -e. Both are included for compatibility reasons with legacy versions of Unix.
-b file Returns true if file is «block-special.» Block-special files are similar to regular files, but are stored on block devices — special areas on the storage device that are written or read one block (sector) at a time.
-c file Returns true if file is «character-special.» Character-special files are written or read byte-by-byte (one character at a time), immediately, to a special device. For example, /dev/urandom is a character-special file.
-d file Returns true if file is a directory.
-e file Returns true if file exists. Does the same thing as -a. Both are included for compatibility reasons with legacy versions of Unix.
-f file Returns true if file exists, and is a regular file.
-g file Returns true if file has the setgid bit set.
-h file Returns true if file is a symbolic link. Does the same thing as -L. Both are included for compatibility reasons with legacy versions of Unix.
-L file Returns true if file is a symbolic link. Does the same thing as -h. Both are included for compatibility reasons with legacy versions of Unix.
-k file Returns true if file has its sticky bit set.
-p file Returns true if the file is a named pipe, e.g., as created with the command mkfifo.
-r file Returns true if file is readable by the user running test.
-s file Returns true if file exists, and is not empty.
-S file Returns true if file is a socket.
-t fd Returns true if file descriptor fd is opened on a terminal.
-u file Returns true if file has the setuid bit set.
-w file Returns true if the user running test has write permission to file, i.e., make changes to it.
-x file Returns true if file is executable by the user running test.
-O file Returns true if file is owned by the user running test.
-G file Returns true if file is owned by the group of the user running test.
-N file Returns true if file was modified since the last time it was read.
file1 -nt file2 Returns true if file1 is newer (has a newer modification date/time) than file2.
file1 -ot file2 Returns true if file1 is older (has an older modification date/time) than file2.
file1 -ef file2 Returns true if file1 is a hard link to file2.
test [-n] string Returns true if string is not empty. Operates the same with or without -n.

For example, if mystr=»», then test «$mystr» and test -n «$mystr» would both be false. If mystr=»Not empty», then test «$mystr» and test -n «$mystr» would both be true.

-z string Returns true if string string is empty, i.e., «».
string1 = string2 Returns true if string1 and string2 are equal, i.e., contain the same characters.
string1 != string2 Returns true if string1 and string2 are not equal.
string1 string2 Returns true if string1 sorts after string2 lexicographically, according to the ASCII numbering. As noted above, use test «$str1» \> «$str2» instead of test $str1 > $str2. The latter command creates or overwrites a file whose name is the value of variable str2.
-o option Returns true if the shell option opt is enabled.
-v var Returns true if the shell variable var is set.
-R var Returns true if the shell variable var is set, and is a name reference. (It’s possible this refers to an indirect reference, as described in Parameter expansion in bash.)
! expr Returns true if and only if the expression expr is null.
expr1 -a expr2 Returns true if expressions expr1 and expr2 are both not null.
expr1 -o expr2 Returns true if either of the expressions expr1 or expr2 are not null.
arg1 -eq arg2 True if argument arg1 equals arg2.
arg1 -ne arg2 True if argument arg1 is not equal to arg2.
arg1 -lt arg2 True if numeric value arg1 is less than arg2.
arg1 -le arg2 True if numeric value arg1 is less than or equal to arg2.
arg1 -gt arg2 True if numeric value arg1 is greater than arg2.
arg1 -ge arg2 True if numeric value arg1 is greater than or equal to arg2.

Notes

All arguments to test must be separated by a space, including all operators.

The operators are lexicographical comparisons, based on ASCII numbering. They are not numerical operators (instead, use -lt, -gt, etc. for comparing numbers).

The precise behavior of test, depending on the number of arguments provided, is as follows:

# args test behavior
0 Always return false.
1 Return true, if and only if the expression is not null.
2 If the first argument is !, return true if and only if the expression is null.

If the first argument is one of the other unary operators (-a, -b, etc.), return true if and only if the unary test of the second argument is true.

Источник

Читайте также:  Msdn system windows forms form
Оцените статью