前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >shell文章系列-shell脚本第十六讲

shell文章系列-shell脚本第十六讲

作者头像
小小科
修改2020-05-13 10:29:14
5730
修改2020-05-13 10:29:14
举报

同学们,欢迎来到马哥教育官网,今天我们一起来学习一下shell文章系列中的shell脚本第十六讲的内容!

1、if..else.. if语句用来实现程序的判断,使用的语法是如下所示: bash if condition then command else command fi 当if语句后面的条件为真时,那么执行的是then后面的那个command命令,当if语句后面的条件为假时,那么执行的是else后面的那个command命令。 根据以前我们讲的那些shell基础,我们再来结合if语句实现一个文件的判断。 我们写一个检测文件的三个读、写、执行权限的脚本

!/bin/bash
if [ -z $1 ]; then echo "请输入一个文件" exit fi if [ -r $1 ]; then echo "this file can read" else echo "this file is not readable" fi if [ -w $1 ];then echo "this file can write" else echo "this file is not writable" fi if [ -x $1 ];then echo "this file can execute" else echo "this file is not executable" fi ```
现在我们创建一个文本文件a.py,然后仅仅赋予此文件一个r权限来看看。
bash [Mike@localhost tmp]$ ll a.py -r--r--r-- 1 root root 429 Apr 7 11:38 a.py [Mike@localhost tmp]$ ./FileCheck.sh a.py this file can read this file is not writable this file is not executable
看到效果了吗?当我们只给文件a.py一个读r的权限时,那么检测这个文件就告诉我们文件可以读,但是不能写,也不能执行。这就是这个脚本的功能作用。
2、检测当前用户是否是管理员root,如果是就安装软件

bash !/bin/bash 检测本机当前用户是否为超级管理员,如果是管理员,则使用 yum 安装 nginx,如果不 是,则提示您非管理员(使用字串对比版本) if [[ “$USER” == “root” ]] then yum install nginx else echo “您不是管理员,没有权限安装软件” fi 我们使用到了[[ ]]这个判断符,我们说最好是引用变量时加上双引号。 3、排序脚本 给系统交互式输入三个数值,然后按照从小到大的顺序进行排序。 这里我们使用到了read -p命令,表示交互式输入一个变量值,并赋值给变量,比如: bash [root@chaofeng tmp]# echo $NAME

[root@chaofeng tmp]

# read -p “请输入你得名字: ” NAME 请输入你得名字: Mike [root@chaofeng tmp]# echo $NAME Mike NAME就是变量,把输入的名字Mike赋值给变量NAME,那么在脚本中如何使用呢? bash !/bin/bash 依次提示用户输入 3 个整数,脚本根据数字大小依次排序输出 3 个数字 read -p “请输入第一个整数:” num1 read -p “请输入第二个整数:” num2 read -p “请输入第三个整数:” num3 tmp=0 if [ $num1 -gt $num2 ];then  tmp=$num1 num1=$num2 num2=$tmp fi if [ $num1 -gt $num3 ];then  tmp=$num1 num1=$num3 num3=$tmp fi if [ $num2 -gt $num3 ];then tmp=$num2 num2=$num3 num3=$tmp fi echo “排序后数据(从小到大)为:$num1,$num2,$num3” “` 现在我们执行一下: bash [root@chaofeng tmp]# ./sort.sh 请输入第一个整数:11 请输入第二个整数:22 请输入第三个整数:18 排序后数据(从小到大)为:11,18,22

好啦!今天的分享到这里就结束了。希望大家持续关注马哥教育官网,每天都会有大量优质内容与大家分享!

本文系转载,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文系转载前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档