Get the App
SLTechnology News&Howtos  ›  Development  › 

How to understand the Shell string operator

Shulou Source: shulou.com Published: 2022-06-02 00:59:17 10月12日 Update

This article will explain in detail how to understand the Shell string operator, the content of the article is of high quality, so the editor will share it with you for reference. I hope you will have some understanding of the relevant knowledge after reading this article.

Shell and other programming languages, support a variety of operators, including: arithmetic operators, relational operations, Boolean operators, string operators, file test operators, and so on, the following focus on Shell string operators.

The commonly used string operators are listed below, assuming that the variable an is "abc" and the variable b is "efg":

Operator description example = checks whether two strings are equal, and equality returns true. [B] returns false. ! = checks whether two strings are equal, and returns true if not. [B] returns true. -z detects whether the string length is 0, and returns true if it is 0. [- z $a] returns false. -n detects whether the string length is 0, and returns true if it is not 0. [- n "$a"] returns true. $checks whether the string is empty, and returns true if it is not empty. [$a] returns true.

Example

Examples of string operators are as follows:

Example #! / bin/bash# author: rookie tutorial # url:www.runoob.coma= "abc" b = "efg" if [$a = $b] then echo "$a = $b: an equals b" else echo "$a = $b: an is not equal to b" fiif [$a! = $b] then echo "$a! = $b: an is not equal to b" else echo "$a! = $b: an equals b" fiif [- z $a] then echo "- z $a: string length is 0" else echo "- z $a: string length is not 0" fiif [- n "$a"] then echo "- n $a: string length is not 0" else echo "- n $a: string length is 0" fiif [$a] then echo "$a: string is not empty" else echo "$a: string is empty" fi "

Execute the script, and the output is as follows:

Abc = efg: an is not equal to babc! = efg: an is not equal to bMurz abc: the string length is not 0Mub n abc: the string length is not 0abc: the string is not empty. I hope the above can help you and learn more about how to understand the Shell string operator. If you think the article is good, you can share it for more people to see.

Tags: Characters strings operations operators length detection instances two content variables articles more knowledge articles good multiple Boolean commonly used tutorials files Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno macOS Microsoft Redmi MySQL Docker