Using test command in linux

Using test Command in Bash Scripts

Learn to use the test command in bash for testing conditions and making comparisons.

The bash test command is used to check the validity of an expression. It checks whether a command or an expression is true or false. Also, it can be used to check the type and permissions of a file.

If the command or expression is valid, the test command returns a 0 else it returns 1 .

Using the test command

The test command has a basic syntax like this:

When using variables in the test command, use double quotes with the variable’s name.

Let’s use the test command to check whether 10 equals 20 and 10 equals 10:

$ test 10 -eq 20 && echo "true" || echo "false"
  • test — test command
  • 10 — the first variable
  • -eq — operator for comparison
  • 20 — second variable

If the given expression is valid, the first command is executed, or else the second command is executed.

💡Instead of using the test command keyword, you can also use the brackets [] . But remember, there is space between the [ mark and the variables to compare:

[ 10 -eq 20 ] && echo "true" || echo "false"

test command examples

Not only integers; you can also compare strings in bash with the test command. Let me share some examples.

String comparison with test Command

Here are some string comparison examples using the test command.

Check if the string is not empty

The -n flag checks if the string length is non-zero. It returns true if the string is non-empty, else it returns false if the string is empty:

$ [ -n "sam" ] && echo "True" || echo "False"

Check that string is not empty in bash

Check if the string is empty

The -z flag checks whether the string length is zero. If the string length is zero, it returns true, else it returns false:

$ [ -z "sam" ] && echo "True" || echo "False"

Check if strings are equals

The ‘=’ operator checks if string1 equals string2. If the two strings are equal, then it returns 0; if the two strings are not equal, then it returns 1:

In this case, the expression is slightly different, instead of typing true or false, the stdout variable is printed using $? .

Check if strings are not equals

The != operator checks if String1 is not equal to String2. If the two strings are not equal, then it returns 0. If two strings are equal, then it returns 1:

Integer comparison with test command

Let’s make some number comparisons with bash test.

Читайте также:  Как установить драйвер ppd linux

Check if numbers are equal

The -eq operator checks if Integer1 equals Integer2. If integer1 equals integer2, then it returns 0, else it returns 1:

Check if the numbers are not equal

Case 2. The -ne operator checks if integer1 is not equal to integer2. If Integer1 is not equal to integer2, then it returns 0, else it returns 1:

Check if a number is equal or greater than the other

The -ge operator checks that integer1 is greater than or equal to integer2. If integer 1 is greater than or equal to integer 2 it returns 0; if not, then it returns 1.

The -gt operator checks if integer1 is greater than integer2. If yes, then it returns 0. Otherwise, it returns 1:

Check if a number is equal or less than the other

The -le operator checks if the integer1 is less than or equal to integer2. If true it returns 0, else it returns 1:

The -lt operator checks if integer1 is less than integer2. If integer 1 is less than integer2, then it returns 0, else it returns 1:

Integer comaprison in bash using the test command

File and directory Operations with test

The test command can be used with files and directories.

This checks whether a file is executable (by the current user) or not. If a file is executable, then it returns 0, else it returns 1:

[ test -x filename ] && echo executable || echo non-executable

You can use other file permissions like r and w in the same fashion. Other common parameters you can use are:

| Command | Description | |---------|--------------------------| | -e | File/directory exists | | -f | is a file | | -d | is a directory | | -s | File size greater than 0 | | -L | is a link | | -S | is a socket |

Using test command in bash scripts

You have seen the one-liners of the test command so far. You can also use the test condition with the if-else condition in the bash scripts.

Let me share a simple example of comparing two numbers passed as arguments to the shell script:

#!/bin/bash ## Check if the numbers are equal or not read -p "Enter the first number: " num1 read -p "Enter the second number: " num2 if test "$num1" -eq "$num2" then echo "$num1 is equal to $num2" else echo "$num1 is not equal to $num2" fi

You can run the bash script with various numbers:

Using test in bash scripts

I hope this tutorial helps you to understand the basics of the test command in the bash.

Источник

Linux. Команда 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
#!/bin/bash if [ -f "$HOME/.bashrc" ]; then echo "Файл существует!" else echo "Файл не существует!" fi

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

  • -z string — истина, если длина string равна нулю
  • -n string — истина, если длина string не ноль
  • string1 = string2 — истина, если строки равны
  • string1 != string2 — истина, если строки не равны
Читайте также:  Kyocera m2735dn драйвер linux

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

  • число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
#!/bin/bash if [ 3 -lt 6 ]; then echo "Истина" else echo "Ложь" fi

Операции AND и OR

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

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

$ [ \( "$count" -ge 0 \) -a \( "$count" -lt 10 \) ]

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

#!/bin/bash if [[ -f "$HOME/.bashrc" && -f "/usr/bin/nano" ]]; then echo "Все в порядке, можно редактировать!" else echo "Ошибка!" fi

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

  • 1С:Предприятие (31)
  • API (29)
  • Bash (43)
  • CLI (99)
  • CMS (139)
  • CSS (50)
  • Frontend (75)
  • HTML (66)
  • JavaScript (150)
  • Laravel (72)
  • Linux (146)
  • MySQL (76)
  • PHP (125)
  • React.js (66)
  • SSH (27)
  • Ubuntu (68)
  • Web-разработка (509)
  • WordPress (73)
  • Yii2 (69)
  • БазаДанных (95)
  • Битрикс (66)
  • Блог (29)
  • Верстка (43)
  • ИнтернетМагаз… (84)
  • КаталогТоваров (87)
  • Класс (30)
  • Клиент (27)
  • Ключ (28)
  • Команда (68)
  • Компонент (60)
  • Конфигурация (62)
  • Корзина (32)
  • ЛокальнаяСеть (28)
  • Модуль (34)
  • Навигация (31)
  • Настройка (140)
  • ПанельУправле… (29)
  • Плагин (33)
  • Пользователь (26)
  • Практика (99)
  • Сервер (74)
  • Событие (27)
  • Теория (105)
  • Установка (66)
  • Файл (47)
  • Форма (58)
  • Фреймворк (192)
  • Функция (36)
  • ШаблонСайта (68)

Источник

Linux test command

Computer Hope

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.

Читайте также:  Команда install в линукс

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

test 100 -gt 99 && echo "Yes, that's true." || echo "No, that's false."

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

test 100 -lt 99 && echo "Yes." || echo "No."

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.

Источник

Оцените статью
Adblock
detector