Shell programming string comparisons and for loops

Source: Internet
Author: User

One, string comparison

    字符串比较使用:= ,==,!=,\>,\<    如:A=‘hello’,B=‘hi’    判断A和B的值是否相等:[  $A  =  $B   ]或者 [  $A  ==  $B   ] 如果相等则返回真    判断A和B的值是否不等:[  $A  !=  $B   ] 如果不相等则返回真    需要注意的是:条件判断符两边要用空格隔开,否则会报错    另外 \>  , \< 用来判断两个字符串大小比较,是通过ASCII来比较,要使用 \ 转义:如 ‘a’ \< ‘b‘ ,‘ab’ \> ‘aa‘    字符串是否为空判断:    如:- n string 判断字符串string是否为空,不为空返回真,-z string 判断字符串是否为空,为空返回真。

Second, for Loop

用法:         for  变量名  in  列表        do                循环体        done

Iii. Scripting Exercises
1. Requirements: Print out the user name of the user's login shell as/bin/bash.
#!/bin/bash
For I cat /etc/passwd in # takes cat /etc/passwd each row in the/etc/passwd and, as a list, assigns each row in the list to the I
Do
Username= echo $i | cut -d: -f1 #取出每行的用户名
Sh= echo $i | cut -d: -f7 #取出每行的shell环境
if [[$sh = = '/bin/bash ']];then #判断是否为/bin/bash
echo "$username"
Fi
Done
2. Ask for 1 to 100 and
#!/bin/bash
Declare-i sum=0 #declare-I declares that the SUM variable is an integer, is assigned a value of 0, and can be directly sum=0

#{1..100}表示生成1到100的数值列表,也可以使用seq 1 1 100生成1到100的列表,第一个1表示从1开始,第二个1表示步长为1,100是结束数字,步长可以省略,默认为1for i in {1..100}do    SUM=$((  $SUM+$i ))doneecho $SUM

Shell programming string comparisons and for loops

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.