shell脚本的简单使用
1)使用`符号执行一个命令的例子(`符号在键盘左上角Esc的下方,与~符号在同一个键上)
#! /bin/sh
DATE=`date` #``中的内容表示变量
echo "today is" $DATE
2)用户输入两个数字,计算两个数字的和
#! /bin/sh
read a
echo 'a=' $a
read b
echo 'b=' $b
c=`expr $a + $b`
echo $c
3)一个循环5次的例子
#! /bin/sh
times=0
while [ "$times" != "5" ];
do
echo $times
times=$[$times + 1]
done
4)多重分支的例子
#! /bin/sh
case "$1" in
start)
echo "is start"
;;
stop)
echo "is stop"
;;
*)
echo "is nothing"
esac
5)for循环语句的例子
#! /bin/sh
sun=0
for i in 1 2 3 4 5;
do
sum=$[$sum + i]
echo $sum
done
shell脚本实例:
设daemon.c是一个循环打印出“hello world”的守护进程程序,gcc编译链接成可执行程序mydaemond。
问题是:如何确保只启动一个守护进程?
通过以下shell脚本语言实现:
vi mydaemon
#! /bin/sh
WHOAMI=`whoami`
PID=`ps -u $WHOAMI | grep mydaemond | awk '{print $1}'`
if ( test "$1" = "") then
echo "mydaemon [start] [stop] [version]"
exit 0
fi
if( test "$1" = "status" ) then
if( test "$PID" = "") then
echo 'not run'
else
echo 'run'
fi
exit 0
fi
if ( test "$1" = "start" ) then
if( test "$PID" = "") then
mydaemond
fi
exit 0
fi
if ( test "$1" = "stop" ) then
if( test "$PID" != "") then
kill $PID
fi
fi
if ( test "$1" = "version") then
echo "version is 1.1.1"
fi
echo "mydaemon [start] [stop] [version]"
:wq
命令行执行: mydaemon start,启动了守护进程;
mydaemon stop,关闭。
如果命令行命令执行不对,上面脚本有很多智能提示。