代码如下:
#!/bin/sh
a=10
b=20
echo "a=$a,b=$b"
if [ $a == $b ]
then
echo "a == b"
else
echo "a != b"
fi
if [[ $a -eq 10 && $b -eq 20 ]]
then
echo "a==10 && b==20"
else
echo "a!=10 || b!=20"
fi
结果运行如下:
linux@ubuntu:~/test_shell$ ./hello.sh
a=10,b=20
./hello.sh: 6: [: 10: unexpected operator
a != b
./hello.sh: 12: ./hello.sh: [[: not found
a!=10 || b!=20
注意:
1,条件表达式要放在方括号之间,并且要有空格,例如: [$a==$b] 是错误的,必须写成 [ $a == $b ] 。
2,逻辑运算符 && 与 || 要用 [[ ]]
查询其版本如下,也不低:
linux@ubuntu:~/test_shell$ bash --version
GNU bash, version 4.2.24(1)-release (i686-pc-linux-gnu)
Copyright (C) 2011 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
后来发现:
#!/bin/sh
改成下面的就可以了:
#!/bin/bash
备注:
Shell 编程跟java、php编程一样,只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了。
Linux的Shell种类众多,常见的有:
- Bourne Shell(/usr/bin/sh或/bin/sh)
- Bourne Again Shell(/bin/bash)
- C Shell(/usr/bin/csh)
- K Shell(/usr/bin/ksh)
- Shell for Root(/sbin/sh)
- ……
一般使用的是 Bash,也就是 Bourne Again Shell,由于易用和免费,Bash在日常工作中被广泛使用。同时,Bash也是大多数Linux系统默认的Shell。
#!/bin/sh,它同样也可以改为#!/bin/bash。
但在ubuntu里最好用#!/bin/bash
#!告诉系统其后路径所指定的程序即是解释此脚本文件的Shell程序。