您的位置:首页 > 运维架构 > Shell

数组结合循环处理重复性操作的shell实例

2013-11-12 09:28 39 查看
最近在论坛看到两个帖子,一个是IP地址批量转换,另一个是备份文件夹下当天数据到另一个文件夹,并将文件夹命名为$用户名+$时间+$文件名的格式,刚好最近在学习shell就用他们来练手了,算是实践结合理论了。

1. IP批量转换
#!/bin/bash
# It is a scripts of IP address quantity convert to hostname.
#E_FILE_EXIST=65
#
#if [ ! -f $1 ];then
#   echo "Usage:`basename $0` filename."
#   exit $E_FILE_EXIST
#fi
#IP=(`cat $1`)
IP=(
8.8.8.8
202.96.209.5 202.96.209.133 202.96.209.6
www.sohu.com
)
echo ------------------------------------------------------------------------
IP_num=${#IP[*]}
for ((i=0;i<"$IP_num";i++))
do
host_name=`host ${IP[$i]} | awk '{print $NF}'`
echo -n -e "${IP[$i]} ---> `echo $host_name` \n"
done
echo ------------------------------------------------------------------------
IP_number=${#IP[*]}
while [ "$IP_number" -gt 0 ]
do
IP_number=$(($IP_number-1))
host_name=`host ${IP[$IP_number]} | awk '{print $NF}'`
echo -n -e "${IP[$IP_number]} ---> `echo $host_name`\n"
done
echo ------------------------------------------------------------------------
exit 0b


2. 备份当天数据

#!/bin/bash
# It is backup data scripts of the same days.
# Variable "DATA_DIR" is backup diritory.
# Variable "BACKUP_DIR" is backup to paths.
DATA_DIR="/usr/local/bin/scripts"
BACKUP_DIR="/tmp"
# ls -l $DATA_DIR
# read -p "Please enter dirtory name(Usage:/paths/dirtory):" BACKUP_DIR
BACKUP_FILE=(`find $DATA_DIR -mtime -1 | awk -F / '{print $NF}'`)
BACKUP_NUM=${#BACKUP_FILE[*]}
NOW_USER=`whoami`
NOW_DATE=`date +_%Y-%m-%d_`
for ((i=1;i<$BACKUP_NUM;i++))
do
/bin/cp -rf $DATA_DIR/${BACKUP_FILE[$i]} $BACKUP_DIR/"$NOW_USER$NOW_DATE${BACKUP_FILE[$i]}"
# 这里有个小技巧,“find -mtime”获取的数据第一个是当前目录,不需要备份,而数组是从0开始;所以这了i从1开始计数刚好规避了这个不需要的备份。
echo "copy file(or diretory) \"$DATA_DIR/${BACKUP_FILE[$i]}\" to \"$BACKUP_DIR/$NOW_USER$NOW_DATE${BACKUP_FILE[$i]}\""
done
exit 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息