shell脚本,首先它是一个脚本,并不是真正编程语言。只是运行在linux的shell中,所以叫shell脚本,shell脚本就是一些命令的集合。通过脚本可以将很重复冗杂的命令行输入,变得轻松容易。
-
这样一步操作就可以完成。其实这个文档呢就是shell脚本了,只是这个shell脚本有它特殊的格式。
-
Shell脚本能帮助我们很方便的去管理服务器,凡是自定义的脚本建议放到/usr/local/sbin/目录下,这样做的目的是,一来可以更好的管理文档;二来自定义脚本基本都放在那里,一下是一些基础的shell脚本操作。
测试脚本:
1.输出当前时间和脚本
#! /bin/bash
#This is a shell script
date
echo "hello shell"
编辑当前脚本,给执行权限:chmod +x test.sh
2、在脚本中使用变量: $
#! /bin/bash
#This is a shell script
#use variables
echo "use variable $"
d=`date +%H:%M:%S`
echo "Beginning at $d"
echo "shleep 1 seconds"
sleep 1
d1=`date +%H:%M:%S`
echo "Ending at $d1"
#The sum of two numbers
a=1
b=2
sum=$[$a+$b]
echo "The sum is $sum"
#can read num
echo "input a number:"
read c
echo "input_number$c"
#new way to read
read -p "Please input a number:" x
read -p "Please input another number:" y
sum=$[$x+$y]
echo "The new sum is $sum"
date命令的效果
测试最终结果
2、基本判断和循环
#!/bin/bash
#if ((judges1));then
#commands1
#elif ((judges2));then
#else
#commands2
#fi
read -p "please input a num:" a
if ((a<60));then
echo "not pass the exam "
elif ((a<85));then
echo "good pass the exam"
else
echo "you are great!"
fi
#loop :for / while:针对seq 1 4是产生1到4的数
for i in `seq 1 4`;do
echo $i
done
while 1>0;do
echo 1
done
3、shell中的函数同其他语言类似
function 函数名() {
command
}
4、练习
- 编写shell脚本,计算1-100的和;
- 编写shell脚本,要求输入一个数字,然后计算出从1到输入数字的和,要求,如果输入的数字小于1,则重新输入,直到输入正确的数字为止;
- 编写shell脚本,把/root/目录下的所有目录(只需要一级)拷贝到/tmp/目录下;
- 编写shell脚本,批量建立用户user_00, user_01, … ,user_100并且所有用户同属于users组;
- 编写shell脚本,截取文件test.log中包含关键词’abc’的行中的第一列(假设分隔符为”:”),然后把截取的数字排序(假设第一列为数字),然后打印出重复次数超过10次的列;
- 编写shell脚本,判断输入的IP是否正确(IP的规则是,n1.n2.n3.n4,其中1<n1<255, 0<n2<255,="" 0<n3<255,="" 0<n4<255<="" span="">)。
1. #! /bin/bash
sum=0
for i in `seq 1 100`; do
sum=$[$i+$sum]
done
echo $sum
2. #! /bin/bash
n=0
while [ $n -lt "1" ]; do
read -p "Please input a number, it must greater than "1":" n
done
sum=0
for i in `seq 1 $n`; do
sum=$[$i+$sum]
done
echo $sum
3. #! /bin/bash
for f in `ls /root/`; do
if [ -d $f ] ; then
cp -r $f /tmp/
fi
done
4. #! /bin/bash
groupadd users
for i in `seq 0 9`; do
useradd -g users user_0$i
done
for j in `seq 10 100`; do
useradd -g users user_$j
done
5. #! /bin/bash
awk -F':' '$0~/abc/ {print $1}' test.log >/tmp/n.txt
sort -n n.txt |uniq -c |sort -n >/tmp/n2.txt
awk '$1>10 {print $2}' /tmp/n2.txt
6. #! /bin/bash
checkip() {
if echo $1 |egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' ; then
a=`echo $1 | awk -F. '{print $1}'`
b=`echo $1 | awk -F. '{print $2}'`
c=`echo $1 | awk -F. '{print $3}'`
d=`echo $1 | awk -F. '{print $4}'`
for n in $a $b $c $d; do
if [ $n -ge 255 ] || [ $n -le 0 ]; then
echo "the number of the IP should less than 255 and greate than 0"
return 2
fi
done
else
echo "The IP you input is something wrong, the format is like 192.168.100.1"
return 1
fi
}
rs=1
while [ $rs -gt 0 ]; do
read -p "Please input the ip:" ip
checkip $ip
rs=`echo $?`
done
echo "IP is right!"