1 编写一个脚本使我们在写一个脚本时自动生成"#!/bin/bash”这一行和注释信息。
#!/bin/bash
if ! grep "^#!" $1 &>/dev/null; then
cat >> $1 << EOF
#!/bin/bash
# Author:
#Date & Time: `date +"%F %T"`
#Description:
EOF
fi
vim +5 $1
任意三个整数,判断最大数。
#!/bin/bash
echo "please enter three number:"
read -p "the first number is :" n1
read -p "the second number is:" n2
read -p "the third number is:" n3
let MAX=$n1
if [ $n2 -ge $n1 ]; then
MAX=$n2
fi
if [ $n3 -ge $MAX ]; then
MAX=$n3
fi
echo "the max number is $MAX."
求100以内偶数的和。
方法一:
#!/bin/bash
sum=0
for I in {1..50}; do
sum=$(($sum+2*$I))
done
echo "the sum is $sum"
方法二:
#!/bin/bash
let SUM=0
for I in $(seq 1 100); do
if [ $[$I%2] == 0 ]; then
let SUM+=$I
fi
done
echo "the sum is $SUM."
利用for语句如何ping C类网,如何ping B类网。
ping C 类网
#!/bin/bash
read –p “C network:” MYNET
PINGNET=`echo $MYNET | sed ‘s/\([0-9.]*\)\ .[0-9]*/\1/g’`
let I=1
while [ $I –le 254 ]; do
ping –c1 –W1 $PINGNET.$I &>/dev/null
[ $? –eq 0 ] && echo “$PINGNET.$I online.” || echo “$PINGNET.$I offline.”
let I++
done
ping B 类网
#!/bin/bash
read –p “B network:” MYNET
PINGNET=`echo $MYNET | sed ‘s/\([0-9]\{1,3\}\.[0-9]\{1,3\}\)\..*/\1/g’`
for P in {0..255}; do
for I in {1..255}; do
if ping -c1 -W2 $PINGNET.$P.$I &>/dev/null; then
echo "$PINGNET.$P.$I is online."
else
echo "$PINGNET.$P.$I is offline."
fi
done
done
提示输入一个用户名,判断用户是否存在,如果存在,显示一下用户默认的shell。
#!bin/bash
read –p “please input a username:” USER
if cut –d:-f1 /etc/passwd | grep “^$USER$” &> /dev/null ;then
MYBASH=`grep “^$USER: ” /etc/passwd | cut –d : -f7`
echo “ ${USER}’s shell is $MYBASH”
else
echo “$USER not exists.”
exit 4
fi
练习:监控系统登录人数,超过四个,显示已经达到四个,五秒钟检查一下,并退出脚本(exit)
#! /bin/bash
read –p “A user:” MYUSER
cut –d : -f1 /etc/passwd | grep “^$MYUSER” &> /dev/null || exit 6
let COUNT=`who | grep “^$MYUSER” | wc –l`
until [ $COUNT –ge 4 ]; do
sleep 5
let COUNT=`who | grep “^$MYUSER” | wc -l`
done
echo “$MYUSER loged 4 times.”
用sed语句实现:查看/etc/sysconfig/network-scripts/ifcfg-eth0 目录下,如果
BOOTPROTO=dhcp,把bootp改成static,并手动添加IP地址和子网掩码:
IPADDR= NETMASK= 。
#!/bin/bash
IFFILE=’/root/ifcfg-eth0’
read –p “IPaddr[192.168.0.1]:” MYIP
[ -z $MYIP ] && MYIP=’192.168.0.1’
echo “please choose your netmask [1,2,3]:”
cat << EOF
‘1’)
MYMASK =’255.255.255.0’
‘2’)
MYMASK =’255.255.0.0’
‘3’)
MYMASK =’255.0.0.0’
EOF
read CHOICE
case $CHOICE in
‘1’)
MYMASK=’255.255.255.0’ ;;
‘2’)
MYMASK=’255.255.0.0’ ;;
‘3’)
MYMASK=’255.0.0.0’ ;;
*)
[ -z $CHOICE ] && read –p “please input your mask:” MYMASK || MYMASK=”255.255.255.0” ;;
esac
[ -z $MYMASK ] && MYMASK=255.255.255.0
if grep –E “^BOOTPROTO=(dhcp)|(bootp)$” $IFFILE&>/dev/null; then
sed –i “ s/^BOOTPROTO=.*/BOOTPROTO=static/g” $IFFILE
grep “^IPADDR=.*” $IFFILE &>/dev/null && sed –i “s/IPADDR=.*/IPADDR=$MYIP/g” $IFFILE || sed –i ” /BOOTPRO=.*/a \IPADDR=$MYIP” $IFFILE
grep “^NETMASK=.*” $IFFILE &>/dev/null && sed –i “s/NETMASK=.*/NETMASK=$MYMASK/g” $IFFILE || sed –i ” /BOOTPRO=.*/a \NETMASK=$NETMASK” $IFFILE
fi