shell if语句用法学习-Shell if怎么用?shell编程
在shell编程中,常常会用if来判断条件,从而控制程序的流程分支。if语句是非常简单,跟其他语言差不多,不过,在shell中,要注意一些细节是很有必要的。
在这里,不给出if的基本语法格式,网上搜索下,很多的。这里给出个简单的例子:
#! /bin/sh -
name=`basename $0 .sh`
if [ $# -ne 2 -a $# -ne 3 ]; then
echo "Usage: $name value1 value2"
echo " $name value1 value2 value3 "
exit 1
fi
if [ $# -eq 2 ]; then
echo "two args: $1, $2"
else
echo "three args: $1 $2 $3"
fi
if [ $# -eq 2 ]; then
if [ $1 -gt $2 ]; then
echo " $1 > $2"
elif [ $1 -lt $2 ]; then
echo " $1 < $2 "
else
echo "$1 = $2"
fi
else
if [ $1 -ge $2 -a $1 -ge $3 ]; then
echo "$1 >=$2 , $1 >=$3"
elif [ $1 -ge $2 -a $1 -lt $3 ]; then
echo "$1 >=$2 ,$1 < $3"
elif [ $1 -lt $2 -a $1 -ge $3 ]; then
echo "$1 < $2, $1 >= $3"
else
echo "$1 < $2, $1 < $3"
fi
fi
exit 0
将上面的内容保存为文件保存为if.sh,并给文件赋予可执行权限。然后通过调用该shell。该shell脚本主要是通过if语句,对不同的参数进行判断输出。上面的脚本基本囊括了常用的if then if else if elif 。if语句中,主要需要注意以下几点:
1、if 与[ 之间必须有空格
2、[ ]与判断条件之间也必须有空格
3、]与; 之间不能有空格
- ·Linux procinfo命令使用教程,学习procinfo命令的用法
- ·Linux spell命令使用教程,学习spell命令的用法及spel
- ·Linux df命令使用教程,学习df命令的用法及df命令语法
- ·Linux id命令使用教程,学习id命令的用法及id命令语法
- ·Linux dip命令使用教程学习,dip命令的用法与实例讲解
- ·Linux zipinfo命令使用教程学习,info命令语法动手详
- ·Linux sort命令使用教程学习惯,sort命令语法详细讲解
- ·Linux ar命令的用法及实例学习-ar命令语法的运用技巧
- ·Linux login命令的用法及实例讲解
- ·linux find命令使用教程及find命令的用法与实例讲解
- ·linux dump命令用法详解。dump命令学习心得。dump命令
- ·linux kill命令使用教程,kill函数命令学习心得。
- ·linux awk数组学习心得及awk数组操作详细介绍 用awk进
- ·Linux Unzip命令使用教程,Linux zip命令使用教程
- ·linux中echo命令详解学习,echo命令的使用方法。
- ·uniq命令详解-linux uniq语法使用教程学习-uniq的用法
- ·AngularJS入门教程-AngularJS教程-从零开始学习Angula
- ·AngularJS入门教程快速开始,从零开始学习AngularJS的
- ·AngularJS入门教程:导言和准备
- ·AngularJS入门教程00:引导程序
- ·AngularJS入门教程01:静态模板
- ·AngularJS入门教程02:AngularJS 模板
- ·AngularJS入门教程03:迭代器过滤
- ·AngularJS入门教程04:双向绑定