1. 字符串的比较问题( > 和 < )

当比较两个字符串大小时,需注意两点

  • 大于小于符号必须转义,否则会把它们当做重定向符号

  • 大于小于逐个字母比较其ASCII值

看例子:

[root@node2 tmp]# cat cmp.sh
#!/bin/bash
#
str1=basketball
str2=soccer
if [ $str1 > $str2 ];then
    echo "$str1 win"
else
    echo "$str2 win"
fi
[root@node2 tmp]# ./cmp.sh
basketball win
[root@node2 tmp]# cat soccer
[root@node2 tmp]# ll soccer
-rw-r--r--. 1 root root 0 Mar 14 03:25 soccer

其输出结果是错误了,并且创建了soccer文件。

正确的应是:

[root@node2 tmp]# cat cmp.sh
#!/bin/bash
#
str1=basketball
str2=soccer
if [ $str1 \> $str2 ];then
    echo "$str1 win"
else
    echo "$str2 win"
fi
[root@node2 tmp]# ./cmp.sh
soccer win

只需添加转义符即可。


2. 双圆括号中可以进行算术扩展和赋值

见以下例子:


[root@node2 tmp]# cat test.sh
#!/bin/bash
#
num=4
if (( $num ** 3 > 60 ));then
    (( num2 = $num ** 3 ))
    echo $num2
fi
[root@node2 tmp]# ./test.sh
64

在(())中赋值,可以两边都加空格,并且可以进行高级运算,**为幂运算,++,--,位运算,等都可以。


3. 在for循环中更改字段分隔符

IFS(internal field separator),全称内部字段分隔符,定义了bash shell用作字段分隔符的一系列字符。默认情况下,bash shell会将下列字符都当做字段分隔符。

  • 空格

  • 制表符

  • 换行符

下面将分隔符修改成‘:’,来处理/etc/passwd中的数据

[root@node2 tmp]# cat ifs.sh
#!/bin/bash
#
IFS_OLD=$IFS
IFS=$'\n'
for row in `cat /etc/passwd`;do
    echo "values in $row - "
    IFS=:
    for value in $row;do
        echo "  $value"
    done
done
IFS=$IFS_OLD
[root@node2 tmp]# ./ifs.sh
values in root:x:0:0:root:/root:/bin/bash -
  root
  x
  0
  0
  root
  /root
  /bin/bash
values in bin:x:1:1:bin:/bin:/sbin/nologin -
  bin
  x
  1
  1
  bin
  /bin
  /sbin/nologin


4. C语言的for命令

[root@node2 tmp]# cat c.sh
#!/bin/bash
#
sum=0
for (( i=1; i<=100; i++ ));do
    sum=$[$sum+$i]
done
echo $sum
[root@node2 tmp]# ./c.sh
5050