shell脚本

什么是shell脚本?

shell脚本就是利用shell功能所写的一个程序,这个程序使用纯文本文件,将一些shell的语法与命令结合在一起所写出的提供给程序员们用啦达到自己的目的。

查看当前环境shell:
echo $SHELL

查看系统自带哪些shell:
cat /etc/shells

第一个shell脚本

#!/bin/bash     //用bash程序来执行,输入sh或者bash加文件名来执行

echo "Hello World ! \n"

在这里插入图片描述

shell脚本实例

交互式脚本:变量内容由用户来输入

#!/bin/bash

read -p "Please input your first name: " firstname
read -p "Please input your last name: " lastname
echo "Your full name is: ${firstname}${lastname} "

在这里插入图片描述

判断式

#!/bin/bash

echo "Please inout a filename, I will check the filename's type and permission.\n"
read -p "Input a filename: " filename   //读取一个文件
test -z ${filename} && echo "you have to input a filename" && exit 0  //判断输入是否为空,若为空则退出
//test -z string  判断字符串是否为0,若为空则为true
test ! -e ${filename} && echo "the filename '&{filename}' isn't exist" && exit 0
//判断文件是否存在,若不存在则退出
test -f ${filename} && filetype="regular file"   //判断是否为普通文件
test -d ${filename} && filetype="directory file"  //判断是否为目录
test -e ${filename} && perm="readable"             //判断是否具有可读的权限
test -w ${filename} && perm="${perm} writable"   //判断是否具有可写的权限
test -x ${filename} && perm="${perm} executable"  //判断是否具有可执行的权限
echo "The filename: ${filename} is a ${filetype}"  
echo "And the permission for you are : ${perm}"

在这里插入图片描述

#!/bin/bash

read -p "Please input Y/N:" yn
if [ "${yn}" == "y" ] || [ "${yn}" == "Y" ]; then
    echo "OK, continue"
elif [ "${yn}" == "n" ] || [ "${yn}" == "N" ]; then
    echo "Oh, interrput!"
else 
    echo "I don't know what your choice is"
fi

在这里插入图片描述

循环

while循环只有在条件成立时才会执行段落

#!/bin/bash

while [ "${yn}" != "yes" -a "${yn}" != "YES" ]
do 
    read -p "Please input yes/YES to stop this program: " yn 
done
echo "ok! you input the correct answer."

until当条件成立时终止循环

#!/bin/bash

until [ "${yn}" == "yes" -o "${yn}" == "YES" ]
do 
    read -p "Please input yes/YES to stop this program: " yn 
done
echo "ok! you input the correct answer."

在这里插入图片描述

#!/bin/bash

for animal in dog cat elephant  //for一直循环次数的循环
do
    echo "There are ${animal}s... "
done

在这里插入图片描述

#!/bin/bash

read -p "Please input a number, I will count for 1+2+...your __ input:" nu
s=0
for (( i=1; i<=${nu}; i=i+1 ))
do
    s=$((${s}+${i}))
done
echo "The result of '1+2+...+${su}' is ==> ${s}"

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值