Shell 和其他编程语言一样,支持多种运算符,包括:
- 算数运算符
- 关系运算符
- 布尔运算符
- 字符串运算符
- 文件测试运算符
原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如 awk 和 expr,expr 最常用。
expr 是一款表达式计算工具,使用它能完成表达式的求值操作。
例如,两个数相加(注意使用的是反引号 ` 而不是单引号 ‘):
#!/bin/bash val=`expr 2 + 2` echo "两数之和为 : $val"
运行实例 »
执行脚本,输出结果如下所示:
两数之和为 : 4
两点注意:
- 表达式和运算符之间要有空格,例如 2+2 是不对的,必须写成 2 + 2,这与我们熟悉的大多数编程语言不一样。
-
完整的表达式要被
` `
包含,注意这个字符不是常用的单引号,在 Esc 键下边。
算术运算符
下表列出了常用的算术运算符,假定变量 a 为 10,变量 b 为 20:
运算符 | 说明 | 举例 |
---|---|---|
+ | 加法 | `expr $a + $b` 结果为 30。 |
– | 减法 | `expr $a – $b` 结果为 -10。 |
* | 乘法 | `expr $a \* $b` 结果为 200。 |
/ | 除法 | `expr $b / $a` 结果为 2。 |
% | 取余 | `expr $b % $a` 结果为 0。 |
= | 赋值 | a=$b 将把变量 b 的值赋给 a。 |
== | 相等。用于比较两个数字,相同则返回 true。 | [ $a == $b ] 返回 false。 |
!= | 不相等。用于比较两个数字,不相同则返回 true。 | [ $a != $b ] 返回 true。 |
注意:条件表达式要放在方括号之间,并且要有空格,例如: [$a==$b] 是错误的,必须写成 [ $a == $b ]。
实例
算术运算符实例如下:
#!/bin/bash # author:码农教程 # url:www.codercto.com a=10 b=20 val=`expr $a + $b` echo "a + b : $val" val=`expr $a - $b` echo "a - b : $val" val=`expr $a \* $b` echo "a * b : $val" val=`expr $b / $a` echo "b / a : $val" val=`expr $b % $a` echo "b % a : $val" if [ $a == $b ] then echo "a 等于 b" fi if [ $a != $b ] then echo "a 不等于 b" fi
执行脚本,输出结果如下所示:
a + b : 30 a - b : -10 a * b : 200 b / a : 2 b % a : 0 a 不等于 b
注意:
- 乘号(*)前边必须加反斜杠(\)才能实现乘法运算;
- if…then…fi 是条件语句,后续将会讲解。
- 在 MAC 中 shell 的 expr 语法是:$((表达式)),此处表达式中的 “*” 不需要转义符号 “\” 。
关系运算符
关系运算符只支持数字,不支持字符串,除非字符串的值是数字。
下表列出了常用的关系运算符,假定变量 a 为 10,变量 b 为 20:
运算符 | 说明 | 举例 |
---|---|---|
-eq | 检测两个数是否相等,相等返回 true。 | [ $a -eq $b ] 返回 false。 |
-ne | 检测两个数是否不相等,不相等返回 true。 | [ $a -ne $b ] 返回 true。 |
-gt | 检测左边的数是否大于右边的,如果是,则返回 true。 | [ $a -gt $b ] 返回 false。 |
-lt | 检测左边的数是否小于右边的,如果是,则返回 true。 | [ $a -lt $b ] 返回 true。 |
-ge | 检测左边的数是否大于等于右边的,如果是,则返回 true。 | [ $a -ge $b ] 返回 false。 |
-le | 检测左边的数是否小于等于右边的,如果是,则返回 true。 | [ $a -le $b ] 返回 true。 |
实例
关系运算符实例如下:
#!/bin/bash # author:码农教程 # url:www.codercto.com a=10 b=20 if [ $a -eq $b ] then echo "$a -eq $b : a 等于 b" else echo "$a -eq $b: a 不等于 b" fi if [ $a -ne $b ] then echo "$a -ne $b: a 不等于 b" else echo "$a -ne $b : a 等于 b" fi if [ $a -gt $b ] then echo "$a -gt $b: a 大于 b" else echo "$a -gt $b: a 不大于 b" fi if [ $a -lt $b ] then echo "$a -lt $b: a 小于 b" else echo "$a -lt $b: a 不小于 b" fi if [ $a -ge $b ] then echo "$a -ge $b: a 大于或等于 b" else echo "$a -ge $b: a 小于 b" fi if [ $a -le $b ] then echo "$a -le $b: a 小于或等于 b" else echo "$a -le $b: a 大于 b" fi
执行脚本,输出结果如下所示:
10 -eq 20: a 不等于 b 10 -ne 20: a 不等于 b 10 -gt 20: a 不大于 b 10 -lt 20: a 小于 b 10 -ge 20: a 小于 b 10 -le 20: a 小于或等于 b
布尔运算符
下表列出了常用的布尔运算符,假定变量 a 为 10,变量 b 为 20:
运算符 | 说明 | 举例 |
---|---|---|
! | 非运算,表达式为 true 则返回 false,否则返回 true。 | [ ! false ] 返回 true。 |
-o | 或运算,有一个表达式为 true 则返回 true。 | [ $a -lt 20 -o $b -gt 100 ] 返回 true。 |
-a | 与运算,两个表达式都为 true 才返回 true。 | [ $a -lt 20 -a $b -gt 100 ] 返回 false。 |
实例
布尔运算符实例如下:
#!/bin/bash # author:码农教程 # url:www.codercto.com a=10 b=20 if [ $a != $b ] then echo "$a != $b : a 不等于 b" else echo "$a != $b: a 等于 b" fi if [ $a -lt 100 -a $b -gt 15 ] then echo "$a 小于 100 且 $b 大于 15 : 返回 true" else echo "$a 小于 100 且 $b 大于 15 : 返回 false" fi if [ $a -lt 100 -o $b -gt 100 ] then echo "$a 小于 100 或 $b 大于 100 : 返回 true" else echo "$a 小于 100 或 $b 大于 100 : 返回 false" fi if [ $a -lt 5 -o $b -gt 100 ] then echo "$a 小于 5 或 $b 大于 100 : 返回 true" else echo "$a 小于 5 或 $b 大于 100 : 返回 false" fi
执行脚本,输出结果如下所示:
10 != 20 : a 不等于 b 10 小于 100 且 20 大于 15 : 返回 true 10 小于 100 或 20 大于 100 : 返回 true 10 小于 5 或 20 大于 100 : 返回 false
逻辑运算符
以下介绍 Shell 的逻辑运算符,假定变量 a 为 10,变量 b 为 20:
运算符 | 说明 | 举例 |
---|---|---|
&& | 逻辑的 AND | [[ $a -lt 100 && $b -gt 100 ]] 返回 false |
|| | 逻辑的 OR | [[ $a -lt 100 || $b -gt 100 ]] 返回 true |
实例
逻辑运算符实例如下:
#!/bin/bash # author:码农教程 # url:www.codercto.com a=10 b=20 if [[ $a -lt 100 && $b -gt 100 ]] then echo "返回 true" else echo "返回 false" fi if [[ $a -lt 100 || $b -gt 100 ]] then echo "返回 true" else echo "返回 false" fi
执行脚本,输出结果如下所示:
返回 false 返回 true
字符串运算符
下表列出了常用的字符串运算符,假定变量 a 为 “abc”,变量 b 为 “efg”:
运算符 | 说明 | 举例 |
---|---|---|
= | 检测两个字符串是否相等,相等返回 true。 | [ $a = $b ] 返回 false。 |
!= | 检测两个字符串是否相等,不相等返回 true。 | [ $a != $b ] 返回 true。 |
-z | 检测字符串长度是否为0,为0返回 true。 | [ -z $a ] 返回 false。 |
-n | 检测字符串长度是否为0,不为0返回 true。 | [ -n “$a” ] 返回 true。 |
str | 检测字符串是否为空,不为空返回 true。 | [ $a ] 返回 true。 |
实例
字符串运算符实例如下:
#!/bin/bash # author:码农教程 # url:www.codercto.com a="abc" b="efg" if [ $a = $b ] then echo "$a = $b : a 等于 b" else echo "$a = $b: a 不等于 b" fi if [ $a != $b ] then echo "$a != $b : a 不等于 b" else echo "$a != $b: a 等于 b" fi if [ -z $a ] then echo "-z $a : 字符串长度为 0" else echo "-z $a : 字符串长度不为 0" fi if [ -n "$a" ] then echo "-n $a : 字符串长度不为 0" else echo "-n $a : 字符串长度为 0" fi if [ $a ] then echo "$a : 字符串不为空" else echo "$a : 字符串为空" fi
执行脚本,输出结果如下所示:
abc = efg: a 不等于 b abc != efg : a 不等于 b -z abc : 字符串长度不为 0 -n abc : 字符串长度不为 0 abc : 字符串不为空
文件测试运算符
文件测试运算符用于检测 Unix 文件的各种属性。
属性检测描述如下:
操作符 | 说明 | 举例 |
---|---|---|
-b file | 检测文件是否是块设备文件,如果是,则返回 true。 | [ -b $file ] 返回 false。 |
-c file | 检测文件是否是字符设备文件,如果是,则返回 true。 | [ -c $file ] 返回 false。 |
-d file | 检测文件是否是目录,如果是,则返回 true。 | [ -d $file ] 返回 false。 |
-f file | 检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。 | [ -f $file ] 返回 true。 |
-g file | 检测文件是否设置了 SGID 位,如果是,则返回 true。 | [ -g $file ] 返回 false。 |
-k file | 检测文件是否设置了粘着位(Sticky Bit),如果是,则返回 true。 | [ -k $file ] 返回 false。 |
-p file | 检测文件是否是有名管道,如果是,则返回 true。 | [ -p $file ] 返回 false。 |
-u file | 检测文件是否设置了 SUID 位,如果是,则返回 true。 | [ -u $file ] 返回 false。 |
-r file | 检测文件是否可读,如果是,则返回 true。 | [ -r $file ] 返回 true。 |
-w file | 检测文件是否可写,如果是,则返回 true。 | [ -w $file ] 返回 true。 |
-x file | 检测文件是否可执行,如果是,则返回 true。 | [ -x $file ] 返回 true。 |
-s file | 检测文件是否为空(文件大小是否大于0),不为空返回 true。 | [ -s $file ] 返回 true。 |
-e file | 检测文件(包括目录)是否存在,如果是,则返回 true。 | [ -e $file ] 返回 true。 |
实例
变量 file 表示文件”/var/www/codercto/test.sh”,它的大小为100字节,具有 rwx 权限。下面的代码,将检测该文件的各种属性:
#!/bin/bash # author:码农教程 # url:www.codercto.com file="/var/www/codercto/test.sh" if [ -r $file ] then echo "文件可读" else echo "文件不可读" fi if [ -w $file ] then echo "文件可写" else echo "文件不可写" fi if [ -x $file ] then echo "文件可执行" else echo "文件不可执行" fi if [ -f $file ] then echo "文件为普通文件" else echo "文件为特殊文件" fi if [ -d $file ] then echo "文件是个目录" else echo "文件不是个目录" fi if [ -s $file ] then echo "文件不为空" else echo "文件为空" fi if [ -e $file ] then echo "文件存在" else echo "文件不存在" fi
执行脚本,输出结果如下所示:
文件可读 文件可写 文件可执行 文件为普通文件 文件不是个目录 文件不为空 文件存在
Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts. In any case I’ll be subscribing to your feed and I hope you write again soon!
Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.
Your article gave me a lot of inspiration, I hope you can explain your point of view in more detail, because I have some doubts, thank you.
SightCare formula aims to maintain 20/20 vision without the need for any surgical process. This supplement is a perfect solution for people facing issues as they grow older. https://sightcare-web.com/
PCWer is here to help you with all questions in tech. Whether that
Find the latest technology news and expert tech product reviews. Learn about the latest gadgets and consumer tech products for entertainment, gaming, lifestyle and more. https://axget.com/
Easier WWW is a leading technology site that is dedicated to produce great how-to, tips and tricks and cool software review. https://easierwww.com/
KeraBiotics is a meticulously-crafted natural formula designed to help people dealing with nail fungus. This solution, inspired by a sacred Amazonian barefoot tribe ritual https://kerabiotics-web.com/
Nagano Lean Body Tonic is a groundbreaking powdered supplement crafted to support your weight loss journey effortlessly. https://naganotonic-try.com/
Sugar Defender is a natural supplement that helps control blood sugar levels, lower the risk of diabetes, improve heart health, and boost energy. https://sugardefender-web.com/
– Shoot MASSIVE Loads For An Amazing Finish! https://semenax-try.com/
ZenCortex Research’s contains only the natural ingredients that are effective in supporting incredible hearing naturally.A unique team of health and industry professionals dedicated to unlocking the secrets of happier living through a healthier body. https://zencortex-try.com/
Serolean, a revolutionary weight loss supplement, zeroes in on serotonin—the key neurotransmitter governing mood, appetite, and fat storage. https://serolean-web.com/
Burn Boost Powder™ is a proven weight loss powder drink that helps to lose weight and boosts the overall metabolism in the body. https://burnboost-web.com
FlowForce Max is an innovative, natural and effective way to address your prostate problems, while addressing your energy, libido, and vitality. https://flowforcemax-web.com/
CLINICALLY PROVEN* To Increase Semen Volume And Intensity https://semenax-try.com/
TestRX™ is a bodybuilding supplement. It’s formulated with high-quality natural ingredients proven to boost natural testosterone and stimulate muscle growth. https://testrx-web.com/
DuoTrim is an innovative weight loss supplement that utilizes the power of natural plants and nutrients to create CSM bacteria https://duotrim-us.com/
BioFit is a Nutritional Supplement That Uses Probiotics To Help You Lose Weight https://biofit-web.com/
Dentitox Pro is a liquid dietary solution created as a serum to support healthy gums and teeth. Dentitox Pro formula is made in the best natural way with unique, powerful botanical ingredients that can support healthy teeth. https://dentitox-us.com/
Sugar Balance is an ultra-potent blood sugar supplement that you can use to help control glucose levels, melt away fat and improve your overall health. https://sugarbalance-us.com/
GlucoFlush is an advanced formula specially designed for pancreas support that will let you promote healthy weight by effectively maintaining the blood sugar level and cleansing and strengthening your gut. https://glucoflush-us.com/
PureLumin Essence is a meticulously-crafted natural formula designed to help women improve the appearance of age spots. https://pureluminessence-web.com/
Alpha Tonic is a powder-based supplement that uses multiple natural herbs and essential vitamins and minerals to help optimize your body’s natural testosterone levels. https://alphatonic-web.com
Vivo Tonic is a remarkable blood sugar support nutritional supplement that offers a wide range of benefits. https://vivotonic-web.com/
Nervogen Pro is an effective dietary supplement designed to help patients with neuropathic pain. When you combine exotic herbs, spices, and other organic substances, your immune system will be strengthened. https://nervogenpro-web.com/
VivoTonic™ is a 11-in-1 vital blood sugar support formula that may improve how the metabolism goes after the calories that consumers eat. https://vivotonic-web.com/
Progenifix is designed to help maximize weight loss results using a mixture of natural, science-backed ingredients. The formula also has secondary benefits, including promoting overall wellness and vitality and assisting your immune system. https://progenifix-web.com/
AquaPeace is an all-natural nutritional formula that uses a proprietary and potent blend of ingredients and nutrients to improve overall ear and hearing health and alleviate the symptoms of tinnitus. https://aquapeace-web.com
FoliPrime is a simple serum containing a blend of vitamins designed to boost hair health. FoliPrime has 100 percent natural substances that enhance and supplement the vitamins in the scalp to promote hair growth. https://foliprime-web.com/
Neuro-Thrive is a brain health supplement that claims to promote good memory and thinking skills and better quality sleep. This nootropic supplement achieves its cause with its potent blend of natural compounds and extracts that are proven to be effective in sharpening mental acuity. https://neurothrive-web.com/
Fast Lean Pro is a herbal supplement that tricks your brain into imagining that you’re fasting and helps you maintain a healthy weight no matter when or what you eat. It offers a novel approach to reducing fat accumulation and promoting long-term weight management. https://fastleanpro-web.com/
Erectin is a clinically-proven dietary supplement designed to enhance male https://erectin-web.com/
PowerBite stands as an innovative dental candy, dedicated to nurturing healthy teeth and gums. Infused with a potent formula, it champions the cause of a robust and radiant smile. Crafted meticulously https://powerbite-web.com/
Boostaro is a dietary supplement designed specifically for men who suffer from health issues. https://boostaro-try.com/
Unlock the incredible potential of Puravive! Supercharge your metabolism and incinerate calories like never before with our unique fusion of 8 exotic components. Bid farewell to those stubborn pounds and welcome a reinvigorated metabolism and boundless vitality. Grab your bottle today and seize this golden opportunity! https://puravive-web.com/
Zoracel is an extraordinary oral care product designed to promote healthy teeth and gums, provide long-lasting fresh breath, support immune health, and care for the ear, nose, and throat. https://zoracel-web.com
Cerebrozen is an excellent liquid ear health supplement purported to relieve tinnitus and improve mental sharpness, among other benefits. The Cerebrozen supplement is made from a combination of natural ingredients, and customers say they have seen results in their hearing, focus, and memory after taking one or two droppers of the liquid solution daily for a week. https://cerebrozen-try.com/
The human body can continue to live thanks to the correct functioning of certain systems. If even one of these systems does not work properly, it can cause problems in human life. https://calmlean-web.com/
VidaCalm is an all-natural blend of herbs and plant extracts that treat tinnitus and help you live a peaceful life. https://vidacalm-web.com/
Are you tired of looking in the mirror and noticing saggy skin? Is saggy skin making you feel like you are trapped in a losing battle against aging? Do you still long for the days when your complexion radiated youth and confidence? https://refirmance-web.com/
Gorilla Flow prostate is an all-natural dietary supplement for men which aims to decrease inflammation in the prostate to decrease common urinary tract issues such as frequent and night-time urination, leakage, or blocked urine stream. https://gorillaflow-web.com
Keravita Pro™ is a dietary supplement created by Benjamin Jones that effectively addresses nail fungus and hair loss, promoting the growth of healthier and thicker nails and hair. The formula is designed to target the underlying causes of these health issues and provide comprehensive treatment. https://keravitapro-web.com
Carbofix is the revolutionary dietary formula that promises to activate weight loss without all the extra hard work. https://carbofix-try.com
PotentStream is designed to address prostate health by targeting the toxic, hard water minerals that can create a dangerous buildup inside your urinary system It’s the only dropper that contains nine powerful natural ingredients that work in perfect synergy to keep your prostate healthy and mineral-free well into old age. https://potentstream-web.com/
dtmliving multifamily news – https://dtmliving.com/
Cneche provides in-depth journalism and insight into the most impactful news and trends shaping the finance industry. https://cneche.com/
Lasixiv provides news and analysis for IT executives. We cover big data, IT strategy, cloud computing, security, mobile technology, infrastructure, software and more. https://lasixiv.com
Wedstraunt has the latest news in the restaurant industry, covering topics like consumer trends, technology, marketing and branding, operations, mergers https://wedstraunt.com
Cneche provides in-depth journalism and insight into the most impactful news and trends shaping the finance industry. https://cneche.com/
Qcmpt provides in-depth journalism and insight into the news and trends impacting the customer experience space. https://qcmpt.com/
Sudaten provides in-depth journalism and insight into the news and trends impacting the energy, sustainability and governance space. https://sudaten.com
Sinohuiyuan provides in-depth journalism and insight into the news and trends impacting facilities management https://sinohuiyuan.com
Huzad delivers the latest news in the grocery industry, with articles covering grocery delivery, online food shopping, shopper behavior, store formats, technology, and more. https://huzad.com/
Grpduk provides news and analysis for human resource executives. We cover topics like recruiting, HR management, employee learning https://grpduk.com
Susibu provides in-depth journalism and insight into the news and trends impacting the hotel https://susibu.com/
Sisanit provides in-depth journalism and insight into the news and trends impacting corporate counsel. https://sisanit.com/
iwinpak provides in-depth journalism and insight into the news and trends impacting the manufacturing sector https://iwinpak.com/
Marketing Dive provides in-depth journalism covering the most impactful news shaping the marketing industry. We cover topics like social media, video marketing, mobile, data and analytics, technology, and more. https://centralhp.com
Christside provides news and analysis for retail executives. We cover topics like retail tech, marketing, e-commerce, logistics, in-store operations, corporate retail news, and more. https://christside.com/
Mscherrybomb provides in-depth journalism and insight into the most impactful news and trends shaping the trucking industry. https://mscherrybomb.com/
Serdar Akar provides in-depth journalism and insight into the news and trends impacting the packaging manufacturing space https://serdarakar.com/
Sugar Defender is the rated blood sugar formula with an advanced blend of 24 proven ingredients that support healthy glucose levels and natural weight loss. https://mimsbrook.com
Sugar Defender is the rated blood sugar formula with an advanced blend of 24 proven ingredients that support healthy glucose levels and natural weight loss. https://mariscosleomar.com/
Sugar Defender is the rated blood sugar formula with an advanced blend of 24 proven ingredients that support healthy glucose levels and natural weight loss. https://manciniproductions.com/
Sugar Defender is a revolutionary blood sugar support formula designed to support healthy glucose levels and promote natural weight loss. https://blackboxvending.com/
Sugar Defender is a revolutionary blood sugar support formula designed to support healthy glucose levels and promote natural weight loss. https://acmesignz.com/
Manufactured in the United States with FDA approval, this product was crafted using only the highest quality ingredients and produced under hygienic conditions in a GMP-certified facility. https://mystylefiles.com/
sugar defender: https://orchidsites.com/
sugar defender: https://peyfon.com/
sugar defender: https://nilayoram.com/
sugar defender: https://sjuesju.com/
sugar defender: https://kandicandles.com/
sugar defender: https://cmymorgans.com/
sugar defender: https://sourceprousa.com/