shell脚本编写
没事看看shell脚本编程,接触了解一下;
Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。
shell环境是:只要有一个能编写代码的文本编辑器和一个能解释执行的脚本解释器就可以了
先来写个简单的:
1.打开文本编辑器(可以使用 vi/vim 命令来创建文件),新建一个文件 test.sh,扩展名为 sh(sh代表shell)
#!/bin/bash
echo "Hello World !"
2.chmod +x ./test.sh #使脚本具有执行权限
./test.sh #执行脚本
运行结果:
1.模拟linnux登录shell
#/bin/bash
echo -n "login:"
read name
echo -n "password:"
read passwd
if [ $name = "cht" -a $passwd = "abc" ];then
echo "the host and password is right!"
else echo "input is error!"
fi
结果如下:
2.比较两个数大小
#/bin/bash
echo "please enter two number"
read a
read b
if test $a -eq $b
then echo "NO.1 = NO.2"
elif test $a -gt $b
then echo "NO.1 > NO.2"
else echo "NO.1 < NO.2"
fi
结果如下:
3.查找/root/目录下是否存在该文件
#/bin/bash
echo "enter a file name:"
read a
if test -e /root/$a
then echo "the file is exist!"
else echo "the file is not exist!"
fi
结果如下:
4.for循环的使用
#/bin/bash
clear
for num in 1 2 3 4 5 6 7 8 9 10
do
echo "$num"
done
结果如下:
5.删除当前目录下大小为0的文件
#/bin/bash
while line=`ls /export/um_lpp_source`
do
if test $line=""
then echo "NULL"
sleep 1
else echo $line
chfs -a size=3G /export/um_lpp_source
exit 0
fi
done
//这个就不运行了,担心文件被删除了
6.测试IP地址
#/bin/bash
for i in 1 2 3 4 5 6 7 8 9
do
echo "the number of $i computer is "
ping -c 1 192.168.0.$i
done
结果如下:
7.普通无参数函数
#/bin/bash
p()
{
echo "hello haibo"
}
p
结果如下:
8.给函数传递参数
#/bin/bash
p_num ()
{
num=$1
echo $num
}
for n in $@
do
p_num $n
done
9.创建文件夹
#/bin/bash
while :
do
echo "please input file's name:"
read a
if test -e /root/$a
then
echo "the file is existing Please input new file name:"
else
mkdir $a
echo "you aye sussesful!"
break
fi
done
结果如下:
10.查找最大文件
#/bin/bash
a=0
for name in *.*
do
b=$(ls -l $name | awk '{print $5}')
if test $b -ge $a
then a=$b
namemax=$name
fi
done
echo "the max file is $namemax"
运行结果:
11.打印当前用户
#/bin/bash
echo "Current User is :"
echo $(ps | grep "$$" | awk '{print $2}')
运行结果如下:
12.case语句
#!/bin/bash
clear
echo "enter a number from 1 to 5:"
read num
case $num in
1) echo "you enter 1"
;;
2) echo "you enter 2"
;;
3) echo "you enter 3"
;;
4) echo "you enter 4"
;;
5) echo "you enter 5"
;;
*) echo "error"
;;
esac
结果如下:
13.内置命令的使用
#/bin/bash
clear
echo "Hello, $USER"
echo
echo "Today 's date id `date`"
echo
echo "the user is :"
who
echo
echo "this is `uname -s`"
echo
echo "that's all folks! "
结果如下:
14.检查端口号是否已启动
#!/bin/bash
n=1
echo "检查php服务..."
while true
do
if test $n -gt 20
then
echo "php服务启动失败"
break
fi
sleep 5
n=$(($n+1))
port='netstat -antp | grep "0.0.0.0:80"'
if [ ${#port} -gt 3 ]; then
echo "xxx服务已经启动"
break;
fi
done
运行结果如下:
上一篇: redis配置主从复制(数据同步)
下一篇: 微信红包算法