什么是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}"