Linux编程技术之Shell脚本编写
目的:
- 掌握简单的Shell编程
2.掌握Shell变量的使用 - 掌握Shell表达式的使用
- 掌握Shell流程控制语句的使用
- 熟悉Shell程序的执行和跟踪
题目:
1、编写脚本dic.sh,在目录/home/test/scripts下批量创建目录:dir+序号(如dir1,dir2,dir3等),并在每个目录下创建文件:登录名+目录名,并赋予文件所有者:读+写+执行权限;同组用户:读+执行权限;其他用户:读+执行权限。
#!/bin/bash
cd /home/test/scripts
pwd
for i in $(seq 1 10)
do
mkdir dir$i
cd dir$i
touch test+dir$i
chmod 755 test+dir$i
more test+dir$i
cd /home/test/scripts
done
结果:
2、编写脚本sum.sh,计算从1加到100的和并返回结果。
#!/bin/bash
#Get the sum of 1 to 100
sum =0
for((i=1;i<=100;i++))
do
sum=$(($sum+$i))
done
echo"The total number is $sum."
结果:
3、编写脚本back.sh,自动归档/home/test/scripts目录下的所有文件,归档文件名为如下形式:back-YYYY-MM-DD;保存在/home/test/backup目录下。
#!/bin/bash
dirname=/home/test/backup
if [ ! -d $dirname ];
then
mkdir $dirname
fi
time=$(date "+%Y-%m-%d")
tar cvf back-$time.tar -c /home/test/scripts/*
mv back-$time.tar $dirname
结果:
4、 设有一个服务器软件,名字为:testd,写一个脚本判断该软件是否运行,如果没有运行,启动该进程。
#!bin/bash
ps -fe|grep testd|grep -v grep
if [ $? -ne 0 ];
then
echo "starting process"
else
echo "process exist"
fi
结果: