SoFunction
Updated on 2025-03-09

Introduction to Comparative Symbols and Special Symbols in Linux shell

Comparison of shell strings and determine whether they are numbers

Binary comparison operator, compare variables or compare numbers. Pay attention to the difference between numbers and strings.

Integer comparison

-eq equals, such as: if [ "$a" -eq "$b" ]
-ne does not equal, such as: if [ "$a" -ne "$b" ]
-gt is greater than, such as: if [ "$a" -gt "$b" ]
-ge is greater than or equal to, such as: if [ "$a" -ge "$b" ]
-lt is less than, such as: if [ "$a" -lt "$b" ]
-le is less than or equal to, such as: if [ "$a" -le "$b" ]
< less than (requires double brackets), such as:(("$a" < "$b"))
<= less than or equal to (requires double brackets), such as:(("$a" <= "$b"))
> greater than (requires double brackets), such as:(("$a" > "$b"))
>= greater than or equal to (requires double brackets), such as:(("$a" >= "$b"))

String comparison

= equal to, such as: if [ "$a" = "$b" ]
== equal to, such as: if [ "$a" == "$b" ], equivalent to =
Note: The function of == behaves differently in [[]] and [], as follows:

1 [[ $a == z* ]] # If $a starts with "z" (pattern matching) then it will be true
2 [[ $a == "z*" ]] # If $a is equal to z* (character matching), then the result is true
3
4 [ $a == z* ] # File globbing and word splitting will happen
5 [ "$a" == "z*" ] # If $a is equal to z* (character matching), then the result is true

For a little explanation, File globbing is a shorthand method about files, such as "*.c" and so on.
However, file globbing is not a strict regular expression, although the structure is similar in most cases.

!= does not equal, such as: if [ "$a" != "$b" ]
This operator will use pattern matching in the [[]] structure.
< less than, in ASCII alphabetical order. For example:
if [[ "$a" < "$b" ]]
if [ "$a" \< "$b" ]
Note: "<" needs to be escaped in the [] structure.
> Greater than, in ASCII alphabetical order. For example:
if [[ "$a" > "$b" ]]
if [ "$a" \> "$b" ]
Note: ">" needs to be escaped in the [] structure.
For specific reference, please refer to Example 26-11 to view the example of this operator application.
-z string is "null". It means the length is 0.
-n string not "null"

Notice:

Using -n in the [] structure, you must use "" to cause variables. Use a string that is not "" to use! -z
Or it is the string itself that is not quoted with "" and put into the [] structure. Although in general
To work, but this is not safe. It is a good habit to be used to using "" to test strings.

awk '{print $2}' | grep '^[0-9.]' > res

Comparison and calculation of numbers under SHELL

Compare:

Method 1: if [ ${A} -lt ${B} ]; then ...
This is the most basic comparison method, using lt(less than), gt(greater than), le(less than or equal), ge(greater than or equal), advantages: not found yet; disadvantages: Only integer comparisons can be made, using lt, gt, etc. is not intuitive

Method 2: if ((${A} < ${B})) then ...
This is a CShell style comparison. Advantages: do not need to use difficult strings such as lt, gt; disadvantages: they can only compare integers

Method 3: if (echo ${A} ${B} | awk '!($1>$2){exit 1}') then ...
This is to use awk comparison. Advantages: You can compare decimals; Disadvantages: The expression is too complicated and difficult to remember

Method 4: if (echo ${A} - ${B} | bc -q | grep -q "^-"); then ...
This is the comparison using bc calculation. Advantages: You can compare decimals; Disadvantages: The expression is more complex and difficult to remember

calculate:
Method 1: typeset C=$(expr ${A} + ${B});
Basic tools in SHELL, advantages: convenient to detect whether a variable is a number; disadvantages: can only calculate integers, and can only calculate addition and subtraction, and cannot calculate multiplication and division.

Method 2: let "C=${A}+${B}"; or let "C=A+B"
Embedded command calculation, advantages: able to calculate multiplication and division and bit operations, etc.; disadvantages: only calculate integers

Method 3: typeset C=$((A+B))
CShell-style calculation, advantages: able to calculate multiplication and division and bit operations, introduction, easy to write; disadvantages: unable to calculate decimals

Method 4: typeset C=${echo ${A} ${B} | awk '{print $1+$2}')
Using awk calculation, advantages: able to calculate decimals, can implement multiple calculation methods, and can be flexible in calculation; disadvantages: expressions are too complex

Method 5: typeset C=${echo ${A} + ${B} | bc -q)
Use awk to calculate, advantages: able to calculate decimals, the calculation method is more than awk, and the calculation is flexible; disadvantages: the expression is too complicated, the number of digits after the decimal point must be set with scale=N, otherwise the result may be truncated into an integer


Special characters

Symbol usage
; Generally, we need to press Enter after outputting a command. If you want to execute multiple commands on a line, you can use it in the middle; split cd /home ; ls
* Indicates any character (regular)
? Any character
[abc] One of the list items
[^abc] Ranges [a-z] [0-9] [A-Z] (all characters and numbers)
{} When using touch_{1,2,3} when looping the list, touch_1, touch_2, touch_3 will be created to loop out these three files, and echo ${ab}c will also be used.
~ home directory cd ~ (The normal call enters the user's own home directory under the /home directory)
$ Extract variable value
`` $() command replaces touch `date +%F_\`date +%T\`` touch $(date +%F_$(date +%T))
$[] Integer calculation echo $[2+3] - * / % Floating point numbers are echo "scale=3; 10/3" | bc -l (bc is used for calculation)
\ escape the string echo \\ output\ escape special characters to prevent SHELL from being interpreted in bash
"" '' String with spaces Treat spaces as part of the string echo "abc xyz" echo 'abc xyz'
`` Command replacement Get the execution result of the command
$() is the same as above, but it makes up for the nesting flaw of ``
@ No special meaning
# Comments (Generally, programming requires comments to allow other team members to understand the functions of the program they write)
$ variable value
$() command replacement
${} range of variable names
% Kill the background often jobs, and get modulus operations (everyone should be familiar with getting modulus)
^ Take non and ! similar
& is processed using process background, && is used for logic and
* Match any string; calculate multiplication
() child process execution
- Minus sign, interval, cd - Return to the upper directory and kill the current jobs

_ (underline) has no special meaning
+ plus sign; kill the current jobs (process)
= Assignment
| Pipeline, || Logical or
\ escape When some special symbols such as $ are a variable that needs to be escaped before being parsed by bash
{} Command List {ls;cd /;}
[] character wildcard, [] is also used for testing commands
: empty command true value
; Command ending character
"" Soft '' Hard ''
< Input redirection
> Output redirection
>& Merge 2 and 1 outputs
, enumeration separator
. Current directory
/ Directory separator
? Single character
Enter command execution