shell编程之常用判断条件、流程控制IF、case、for、WHILE循环、read读取控制台输入、函数basename、dirname以及自定义函数

一、常用判断条件

1、两个整数之间比较

2、文件权限判断

  • -r 有读的权限
  • -w 有写的权限
  • -x 有执行的权限

 3、文件类型判断

  • -f 文件存在并且是一个常规文件
  • -e 文件存在
  • -d 文件存在并是一个目录
# 判断23是否大于2
[linux@localhost datas]$ [ 23 -gt 2 ]
[linux@localhost datas]$ echo $?
0

# 判断helloworld.sh是否有写入权限
[linux@localhost datas]$ [ -w hellowrld.sh ]
[linux@localhost datas]$ echo $?
1

# 判断目录中文件是否存在
[linux@localhost datas]$ [ -e /home/linux/datas ]
[linux@localhost datas]$ echo $?
0

4、多条件判断

&& ||

[dhapp@conch01 shell]$ [ -x parameter.sh ] && [ -e  parameter.sh ]
[dhapp@conch01 shell]$ echo $?
0
[dhapp@conch01 shell]$ [ -x parameter.sh ] && [ -e  parameter2.sh ]
[dhapp@conch01 shell]$ echo $?
1
[dhapp@conch01 shell]$ ll
total 4
-rwxr-xr-x. 1 dhapp dhapp 28 May  1 22:49 parameter.sh
[dhapp@conch01 shell]$

上面判断是否有parameter.sh文件的执行权限以及parameter.sh文件是否存在


二、流程控制

1、IF判断

[linux@localhost datas]$ cat if.sh
#!/bin/bash
if [ $1 -eq 1 ]
then
	echo "班长真帅"
elif [ $1 -eq 2 ]
then
	echo "班长真丑"
fi
[linux@localhost datas]$ bash if.sh 2
班长真丑

2、case 语句

[linux@localhost datas]$ cat case.sh
#!/bin/bash
case $1 in
1)
	echo "班长"
;;
2)
	echo "学习委员"
;;
3)
	echo "体育委员"
;;
esac
[linux@localhost datas]$ bash case.sh 2
学习委员

3、for循环

语法1

[linux@localhost datas]$ cat for.sh
#!/bin/bash
s=0
for((i=1;i<=100;i++))
do
	s=$[$s+$i]	
done
echo $s
[linux@localhost datas]$ bash for.sh
5050

语法2

[linux@localhost datas]$ cat for2.sh
#!/bin/bash
for i in $*
do
	echo $i
done
[linux@localhost datas]$ bash for2.sh 1 2
1
2

4、WHILE循环

[linux@localhost datas]$ cat while.sh
#!/bin/bash
s=0
i=1
while [ $i -le 100 ]
do
	s=$[$s + $i]
	i=$[$i + 1]
done
echo $s

[linux@localhost datas]$ bash while.sh
5050

三、read读取控制台输入

1、语法

   read(选项)(参数)

  • -p 指定读取值时的提示符
  • -t 指定读取值时等待的时间(秒)
# 提示7秒内,读取控制台输入的名称
[linux@localhost datas]$ cat read.sh
#!/bin/bash
read -t 7 -p "在7s内请输入你的名字" NAME
echo $NAME
[linux@localhost datas]$ bash read.sh
在7s

四、函数

1、系统函数

1.1、basename

basename [string / pathname] [suffix] (描述:basename命令会删掉所有的前缀包括最后一个‘/’字符,然后将字符串显示出来)
# 方式1
[linux@localhost datas]$ basename /home/linux/banzhang.txt
banzhang.txt

# 方式2
[linux@localhost datas]$ basename /home/linux/banzhang.txt .txt
banzhang

1.2、dirname

dirname 文件绝对路径 (描述:从给定的包含绝对路径的文件名中去除文件名(非目录的部分),然后返回剩下的路径(目录的部分))
[linux@localhost datas]$ dirname /home/linux/banzhang.txt
/home/linux

1.3、自定义函数

# 格式
[ function ] funname[()]
{
	Action:
	[return int;]
}
funname
# DESC 计算输入两个参数的值
[linux@localhost datas]$ cat sum.sh
#!/bin/bash
function sum(){
	s=0;
	s=$[$1 + $2]
	echo $s
}
read -p "input your param1:" P1
read -p "input your param2:" P2
sum $P1 $P2
[linux@localhost datas]$ bash sum.sh
input your param1:1
input your param2:2
3

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值