说明:本文仅供学习交流,不得用于其他目的,转载请标明出处,欢迎转载
学任何一种编程语言,我们的学习顺序基本都是:
基本数据类型-->语句(顺序,选择,循环)-->数组--->函数--->文件---->高级编程
本文提到的一种结构是选择结构中的if语句:
接触过高级语言的人都知道,我们的if语句结构为(以C语言为例):
if(条件1)
{
...
}
else if(条件2)
{
...
}
else
{
...
}
那么在SHELL脚本编程中,对应的该结构的分支如下:
if[ 条件1 ] ; then
...
elif[ 条件2 ]; then
...
else
...
fi
注意:[ 条件 ]中的条件与两端的中括号之间一定要有空格符,否则出错。
现将下面那段C++语句转换为对应的SHELL script
#include<iostream>
using namespace std;
int main()
{
int i;
cout<<"input a number:";
cin>>i;
if(i>==1 && i<=10)
{
cout<<"aaa"<<endl;
}
else if(i>10 && i<=15)
{
cout<<"bbb"<<endl;
}
else
{
cout<<"error"<<endl;
}
return 0;
}
对应的Shell script为:
1.#!/bin/bash
2.# Program
3.# using if...elif...else...fi
4.# History
5.# 2014/04/15 House firstRelease
6.PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
7.export PATH
8.declare -i x
9.read -p "Please input a integer:" x
10.if [ $x -ge 1 ]&& [ $x -le 10 ];then
11. echo "aaa"
12.elif [ $x -ge 11 ] && [ $x -le 15]; then
13. echo "bbb"
14.else
15. echo "error!"
16.fi
17.exit 0
特别值得注意的是,上面的$x中的$一定不能少,否则程序出错!
另外:要学会Shell中的分支语句,必须先掌握一些逻辑表达式,如-eq,-ne,-gt...