7. Shell 脚本编写

时间:2023-11-23 21:36:38

一、Shell 脚本编写

1、提示用户输入一个字符串,如果是 hello,打出 yes,并每秒输出 "hello,world",否则就输出 no,实现如下:

#!/bin/bash
#Filename:hello.sh
echo "Please input 'hello'"
read -p "> " str  // 得到键盘输入
echo $str
if [ "$str" == hello ]
then
        echo "yes"
        while true
        do
                echo "hello, world"
                sleep 1   // 睡眠1秒
        done
else
echo "no"
fi

2、实现一个 find.sh,运行 ./find.sh  /tmp/test.txt ,当 /tmp/test.txt 为文件且存在时输出 yes, 否则输出 no,实现如下:

#!/bin/bash
#Filename:find.sh
args1=$1         ( $0 为要执行的文件路径,$1 为输入的第一个参数,以此类推)
 if [ -e "$args1" ]    // 如果该变量代表的值是一个文件
then
        echo "yes"
else
        echo "no"
fi
判断文件的参数如下:
-e 文件存在 
-f file 是一个 regular 文件(不是目录或者设备文件) 
-s 文件长度不为 0 
-d 文件是个目录 
-b 文件是个块设备(软盘,cdrom 等等) 
-c 文件是个字符设备(键盘,modem,声卡等等) 
-p 文件是个管道 
-h 文件是个符号链接 
-L 文件是个符号链接 
-S 文件是个 socket 
-t 关联到一个终端设备的文件描述符 这个选项一般都用来检测是否在一个给定脚本中的 stdin[-t0]或[-t1]是一个终端 
-r 文件具有读权限(对于用户运行这个 test) 
-w 文件具有写权限(对于用户运行这个 test) 
-x 文件具有执行权限(对于用户运行这个 test)

3、实现一个 ping.sh

  • 运行 ./ping.sh start 后在后台运行 ping 命令,ping 127.0.0.1,并把 ping 结果输出到 /tmp/ping.log
  • 运行 ./ping.sh status 显示 ping 命令是否正在运行
  • 运行 ./ping.sh stop 停止 ping 命令,如果正在运行的话。

# 方法一:输入 stop 时,直接关闭所有的 ping 进程

#!/bin/bash
#Filaname:ping.sh
if [ "$1" == "start" ]
then
        ping 127.0.0.1 > /tmp/ping.log &
elif [ "$1" == "status" ]
then
        ps -ef | grep "ping 127.0.0.1"
elif [ "$1" == "stop" ]
then
        killall ping  (会干掉所有的ping 进程,包括子进程)
fi

#方法二:得到ping 127.0.0.1 的进程 ID ,再用kill 结束掉

#!/bin/bash
#Filaname:ping.sh
if [ "$1" == "start" ]
then
        ping 127.0.0.1 > /tmp/ping.log &
elif [ "$1" == "status" ]
then
        ps -ef | grep "ping 127.0.0.1"
elif [ "$1" == "stop" ]
then
        pid=`ps -ef |grep ping | grep "127.0.0.1" | awk '{print $2}'`
        if [ "pid" -gt 0 ];then
                kill $pid
                echo kill $pid
        else
                echo "要关闭的进程不存在"
        fi
fi

4、将上面的 ping.sh 加入开机自启动

# 方法一:

系统的rc.local 文件是在 系统启动之后才加载的,可以把脚本添加到这个文件中
打开 /etc/rc.d/rc.local 文件(root 用户):vim /etc/rc.d/rc.local
加入下面两行:
cd /home/demon   # 进入到当前目录
su demon -c "./ping.sh start"

# 方法二:

# 修改 ping.sh 的权限
# chmod 755 ping.sh
# 将 ping.sh 移动到 /etc/rc.d/init.d/ 目录下
# 使用 chkconfig 命令将脚本设为开机启动
# chkconfig --add ping.sh