1.编程第一课,输出hello world
#!/bin/bash
echo "Hello world" ##打印输出hello world
2.自动清空日志
#!/bin/bash
cd /var/log ##切换目录到/var/log
>messages ##清空日志
echo "Logs cleaned up..." ##打印输出已经清理完成
当然这个不是很完善,如果我们不是root用户呢,下面给出一个完善的脚本
#!/bin/bash
LOG_DIR=/var/log
ROOT_UID=0 ##定义变量
if [ "$UID" -ne "$ROOT_UID" ];then ##判断是否root用户,不是的话执行括号内程序
echo "Error:you should be root to run this script!"
exit 1 ##退出此程序
fi
cd $LOG_DIR || { ##切换目录,||是前面执行不成功,才会执行
echo "Cannot access to directory."
exit 1
}
cat /dev/null > messages && {
echo "Logs cleaned up..."
exit 0
}
echo "logs cleaned failed..."\
exit 1
运行结果
3.启动并开机自启动httpd的脚本
#!/bin/bash
yum install httpd -y >/dev/null
systemctl start httpd
systemctl enable httpd
firewall-cmd --add-service=http >/dev/null
firewall-cmd --reload >/dev/null
echo "all done"
4.面试题
脚本如下
#!/bin/bash
username=`whoami`
然后执行
sh test.sh
echo $username
问题:echo $username命令的输出结果是什么?
a)当前用户
b)root
c)空(无输出)
答案是c,这是因为sh的执行方式,并不会返还值到父shell,所以输出为空,我们试着用source执行
5.打包日志
#!/bin/bash
tar zcf log_$(date +%F).tar.gz /var/log/
6.计算两个数的加减乘除
#!/bin/bash
read -t 5 -p "请输入两个整数:" a b
echo "a+b=$[a+b]"
echo "a-b=$[a-b]"
echo "a*b=$[a*b]"
echo "a/b=$[a/b]"
echo "a**b=$[a**b]"
echo "a%b=$[a%b]"
7.写一个脚本检测网络,下面这个脚本,可以检测60的ip
#!/bin/bash
for ((a=0;a<60;a++))
do
ping -c1 -w1 172.25.254.$a &> /dev/null && echo 172.25.254.$a is up || echo 172.25.254.$a is down ##&&表示成功会执行,||表示不成功会执行
done
8.测试一个文件是不是/etc/passwd
#!/bin/bash
[ "$1" = "/etc/passwd" ] && echo YES || echo NO
9.判断输入的数字是否在10以内
1.输入是否为空
2.是否在10以内
3.1<$a<10 --> yes
4.$a<1 $a>10 --> no
#!/bin/bash
[ -z "$1" ] && { ##判断是否为空
echo "please input a number!"
exit 1
}
[ "$1" -gt "0" -a "$1" -lt "10" ] && { ##判断是不是大于0小于10
echo "YES"
}||{
echo "NO"
}
10.判断文件类型
#!/bin/bash
read -p "qing shu ru wen jian ming: " b
if [ -f "$b" ];then
echo "pu tong wen jian"
elif [ -b "$b" ];then
echo "kuai she bei"
elif [ -s "$b" ];then
echo "tao jie zi she bei"
elif [ -c "$b" ] ;then
echo "zi fu she bei"
elif [ -L "$b" ];then
echo "ruan lian jie"
else
echo "I have no idea what kind of file it is"
fi