Linux bash if greater

How to Compare Numbers and Strings in Linux Shell Script

In this tutorial on Linux bash shell scripting, we are going to learn how to compare numbers, strings and files in shell script using if statement. Comparisons in a script are very useful & after comparison result, script will execute the commands and we must know how we can use them to our advantage.

Syntax of comparisons in shell script

if [ conditions/comparisons] then commands fi
if [2 -gt 3] then print "2 is greater" else print "2 is not greater" fi

This was just a simple example of numeric comparison & we can use more complex statement or conditions in our scripts. Now let’s learn numeric comparisons in bit more detail.

Compare Numbers in Linux Shell Script

This is one the most common evaluation method i.e. comparing two or more numbers. We will now create a script for doing numeric comparison, but before we do that we need to know the parameters that are used to compare numerical values . Below mentioned is the list of parameters used for numeric comparisons

  • num1 -eq num2 check if 1st number is equal to 2nd number
  • num1 -ge num2 checks if 1st number is greater than or equal to 2nd number
  • num1 -gt num2 checks if 1st number is greater than 2nd number
  • num1 -le num2 checks if 1st number is less than or equal to 2nd number
  • num1 -lt num2 checks if 1st number is less than 2nd number
  • num1 -ne num2 checks if 1st number is not equal to 2nd number

Now that we know all the parameters that are used for numeric comparisons, let’s use these in a script,

#!/bin/bash # Script to do numeric comparisons var1=10 var2=20 if [ $var2 -gt $var1 ] then echo "$var2 is greater than $var1" fi # Second comparison If [ $var1 -gt 30] then echo "$var is greater than 30" else echo "$var1 is less than 30" fi

This is the process to do numeric comparison, now let’s move onto string comparisons.

Compare Strings in Linux Shell Script

When creating a bash script, we might also be required to compare two or more strings & comparing strings can be a little tricky. For doing strings comparisons, parameters used are

  • var1 = var2 checks if var1 is the same as string var2
  • var1 != var2 checks if var1 is not the same as var2
  • var1 < var2 checks if var1 is less than var2
  • var1 > var2 checks if var1 is greater than var2
  • -n var1 checks if var1 has a length greater than zero
  • -z var1 checks if var1 has a length of zero

Solution is simple , when using any of these symbols in scripts, they should be used with escape character i.e. use it as “/>” or “/

Now let’s create a script doing the string comparisons.

In the script, we will firstly be checking string equality, this script will check if username & our defined variables are same and will provide an output based on that. Secondly, we will do greater than or less than comparison. In these cases, last alphabet i.e. z will be highest & alphabet a will be lowest when compared. And capital letters will be considered less than a small letter.

#!/bin/bash # Script to do string equality comparison name=linuxtechi if [ $USER = $name ] then echo "User exists" else echo "User not found" fi # script to check string comparisons var1=a var2=z var3=Z if [ $var1 \> $var2 ] then echo "$var1 is greater" else echo "$var2 is greater" fi # Lower case & upper case comparisons if [ $var3 \> $var1 ] then echo "$var3 is greater" else echo "$var1 is greater" fi

We will now be creating another script that will use “-n” & “-z” with strings to check if they hold any value

#!/bin/bash # Script to see if the variable holds value or not var1=" " var2=linuxtechi if [ -n $var1 ] then echo "string is not empty" else echo "string provided is empty" fi

Here we only used ‘-n’ parameter but we can also use “-z“. The only difference is that with ‘-z’, it searches for string with zero length while “-n” parameter searches for value that is greater than zero.

Читайте также:  Budgie on linux mint

File comparison in Linux Shell Script

This might be the most important function of comparison & is probably the most used than any other comparison. The Parameters that are used for file comparison are

  • -d file checks if the file exists and is it’s a directory
  • -e file checks if the file exists on system
  • -w file checks if the file exists on system and if it is writable
  • -r file checks if the file exists on system and it is readable
  • -s file checks if the file exists on system and it is not empty
  • -f file checks if the file exists on system and it is a file
  • -O file checks if the file exists on system and if it’s is owned by the current user
  • -G file checks if the file exists and the default group is the same as the current user
  • -x file checks if the file exists on system and is executable
  • file A -nt file B checks if file A is newer than file B
  • file A -ot file B checks if file A is older than file B

Here is a script using the file comparison

#!/bin/bash # Script to check file comparison dir=/home/linuxtechi if [ -d $dir ] then echo "$dir is a directory" cd $dir ls -a else echo "$dir is not exist" fi

Similarly we can also use other parameters in our scripts to compare files. This completes our tutorial on how we can use numeric, string and file comparisons in bash scripts. Remember, best way to learn is to practice these yourself.

3 thoughts on “How to Compare Numbers and Strings in Linux Shell Script”

Solution is simple , when using any of these symbols in scripts, they should be used with escape character i.e. use it as “/>” or “/ <“.
I think you meant to escape with a left oblique stroke rather than a right one (\ not /). Reply

If number is 6 and want to test if greater than, using -gt up until 9 is fine, over, like 10 as the base number, then it fails. Why?
Example:
NUM=6
if [ “$NUM” -gt “10”]
echo “$NUM is higher than 10”
else
echo “$NUM is lower than 10”
fi Reply

Читайте также:  Request irq linux kernel

Источник

Linux bash if greater

if [ «$a» -eq «$b» ]

if [ «$a» -ne «$b» ]

if [ «$a» -gt «$b» ]

if [ «$a» -ge «$b» ]

if [ «$a» -lt «$b» ]

if [ «$a» -le «$b» ]

меньше или равно (внутри двойных круглых скобок)

больше (внутри двойных круглых скобок)

больше или равно (внутри двойных круглых скобок)

[[ $a == z* ]] # истина, если $a начинается с символа "z" (сравнение по шаблону) [[ $a == "z*" ]] # истина, если $a равна z* [ $a == z* ] # имеют место подстановка имен файлов и разбиение на слова [ "$a" == "z*" ] # истина, если $a равна z* # Спасибо S.C.

меньше, в смысле величины ASCII-кодов

больше, в смысле величины ASCII-кодов

Обратите внимание! Символ «>» необходимо экранировать внутри [ ].

См. Пример 25-6 относительно применения этого оператора сравнения.

строка «пустая» , т.е. имеет нулевую длину

Пример 7-5. Операции сравнения

#!/bin/bash a=4 b=5 # Здесь переменные "a" и "b" могут быть как целыми числами, так и строками. # Здесь наблюдается некоторое размывание границ #+ между целочисленными и строковыми переменными, #+ поскольку переменные в Bash не имеют типов. # Bash выполняет целочисленные операции над теми переменными, #+ которые содержат только цифры # Будьте внимательны! echo if [ "$a" -ne "$b" ] then echo "$a не равно $b" echo "(целочисленное сравнение)" fi echo if [ "$a" != "$b" ] then echo "$a не равно $b." echo "(сравнение строк)" # "4" != "5" # ASCII 52 != ASCII 53 fi # Оба варианта, "-ne" и "!=", работают правильно. echo exit 0

Пример 7-6. Проверка — является ли строка пустой

#!/bin/bash # str-test.sh: Проверка пустых строк и строк, не заключенных в кавычки, # Используется конструкция if [ . ] # Если строка не инициализирована, то она не имеет никакого определенного значения. # Такое состояние называется "null" (пустая) (это не то же самое, что ноль). if [ -n $string1 ] # $string1 не была объявлена или инициализирована. then echo "Строка \"string1\" не пустая." else echo "Строка \"string1\" пустая." fi # Неверный результат. # Выводится сообщение о том, что $string1 не пустая, #+не смотря на то, что она не была инициализирована. echo # Попробуем еще раз. if [ -n "$string1" ] # На этот раз, переменная $string1 заключена в кавычки. then echo "Строка \"string1\" не пустая." else echo "Строка \"string1\" пустая." fi # Внутри квадратных скобок заключайте строки в кавычки! echo if [ $string1 ] # Опустим оператор -n. then echo "Строка \"string1\" не пустая." else echo "Строка \"string1\" пустая." fi # Все работает прекрасно. # Квадратные скобки -- [ ], без посторонней помощи определяют, что строка пустая. # Тем не менее, хорошим тоном считается заключать строки в кавычки ("$string1"). # # Как указывает Stephane Chazelas, # if [ $string 1 ] один аргумент "]" # if [ "$string 1" ] два аргумента, пустая "$string1" и "]" echo string1=initialized if [ $string1 ] # Опять, попробуем строку без ничего. then echo "Строка \"string1\" не пустая." else echo "Строка \"string1\" пустая." fi # И снова получим верный результат. # И опять-таки, лучше поместить строку в кавычки ("$string1"), поскольку. string1="a = b" if [ $string1 ] # И снова, попробуем строку без ничего.. then echo "Строка \"string1\" не пустая." else echo "Строка \"string1\" пустая." fi # Строка без кавычек дает неверный результат! exit 0 # Спвсибо Florian Wisser, за предупреждение.

Пример 7-7. zmost

#!/bin/bash #Просмотр gz-файлов с помощью утилиты 'most' NOARGS=65 NOTFOUND=66 NOTGZIP=67 if [ $# -eq 0 ] # то же, что и: if [ -z "$1" ] # $1 должен существовать, но может быть пустым: zmost "" arg2 arg3 then echo "Порядок использования: `basename $0` filename" >&2 # Сообщение об ошибке на stderr. exit $NOARGS # Код возврата 65 (код ошибки). fi filename=$1 if [ ! -f "$filename" ] # Кавычки необходимы на тот случай, если имя файла содержит пробелы. then echo "Файл $filename не найден!" >&2 # Сообщение об ошибке на stderr. exit $NOTFOUND fi if [ $ != "gz" ] # Квадратные скобки нужны для выполнения подстановки значения переменной then echo "Файл $1 не является gz-файлом!" exit $NOTGZIP fi zcat $1 | most # Используется утилита 'most' (очень похожа на 'less'). # Последние версии 'most' могут просматривать сжатые файлы. # Можно вставить 'more' или 'less', если пожелаете. exit $? # Сценарий возвращает код возврата, полученный по конвейеру. # На самом деле команда "exit $?" не является обязательной, # так как работа скрипта завершится здесь в любом случае,

построение сложных условий проверки

Читайте также:  Open file settings linux

exp1 -a exp2 возвращает true, если оба выражения, и exp1, и exp2 истинны.

exp1 -o exp2 возвращает true, если хотябы одно из выражений, exp1 или exp2 истинно.

Примечания

Как указывает S.C., даже заключение строки в кавычки, при построении сложных условий проверки, может оказаться недостаточным. [ -n «$string» -o «$a» = «$b» ] в некоторых версиях Bash такая проверка может вызвать сообщение об ошибке, если строка $string пустая. Безопаснее, в смысле отказоустойчивости, было бы добавить какой-либо символ к, возможно пустой, строке: [ «x$string» != x -o «x$a» = «x$b» ] (символ «x» не учитывается).

Источник

How to check if a file’s size is greater than a certain value in Bash

With this code, I can get the file name in the variable $FILESIZE, but I am unable to compare it with a fixed integer value.

#!/bin/bash filename=./testfile.txt maxsize=5 filesize=$(stat -c%s "$filename") echo "Size of $filename = $filesize bytes." if (( filesize > maxsize )); then echo "nope" else echo "fine" fi 

if [ (( $FILESIZE > MAXSIZE)) ]; -> if (( FILESIZE > MAXSIZE )); The arithmetic operators can serve as a conditional expression. (you don’t need the $ within ((. )) )

2 Answers 2

A couple of syntactic issues.

  1. The variable definitions in Bash do not take spaces. It should have been MAXSIZE=500000 , without spaces.
  2. The way comparison operation is done is incorrect. Instead of if [ (( $FILESIZE > MAXSIZE)) ]; , you could very well use Bash’s own arithmetic operator alone and skip the [ operator to just if (( FILESIZE > MAXSIZE)); then

If you are worried about syntax issues in your script, use ShellCheck to syntax check your scripts and fix the errors as seen from it.

As a general coding practice, use lowercase user-defined variables in Bash to avoid confusing them with the special environment variables which are interpreted for different purposes by the shell (e.g., $HOME and $SHELL ).

You can use the find command to accomplish this as well. See the below examples.

You can change the stat command for any command you need.

ls -lh test.txt -rw-r--r-- 1 root root 25M Jan 20 19:36 test.txt find ~/test.txt -size 25M -exec stat '<>' \; File: '/root/test.txt' Size: 26214400 Blocks: 51200 IO Block: 4096 regular file Device: fe04h/65028d Inode: 402704 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2022-01-20 19:36:51.222371293 +0000 Modify: 2022-01-20 19:36:51.242373113 +0000 Change: 2022-01-20 19:36:51.242373113 +0000 Birth: - 

If the file does not have the size you are looking for, it won’t do anything.

find ~/test.txt -size 99M -exec true \; 

Источник

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