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

常用简单脚本方法

2012-01-08 20:01 274 查看

常用简单脚本方法

编写第一个脚本(script)

显示”Hello,World!”

#!/bin/bash
#Program:
# This program shows “Hello,World!” in you screen.
#History:
#2010/12/15 Frog Hong First release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
echo –e “Hello World! \a \n “
exit 0

用户输入first与last name,屏幕显示“Your full name is : ”的内容

#!/bin/bash
read –p “Please input your first name: “ firstname
read –p “Please input your last name: “ lastname
echo –e “\n Your full name is :$firstname $lastname”

利用日期进行文件的创建

#!/bin/bash
echo -e "I will user ‘touch’ command to create 3 files."
read -p "Please input your filename: " fileuser
filename=${fileuser:-"filename"}
date1=$(date --date='2 days ago' +%Y%m%d)
date2=$(date --date='1 days ago' +%Y%m%d)
date3=$(date +%Y%m%d)
file1=${filename}${date1}
file2=${filename}${date2}
file3=${filename}${date3}
touch "$file1"
touch "$file2"
touch "$file3"

数值运算(简单的加减乘除)

#!/bin/bash
echo -e "Your should input 2 number, I will cross them!\n"
read -p "first number: " firstnum
read -p "second number:" secondnum
total_1=$(($firstnum*$secondnum))
total_2=$(($firstnum/$secondnum))
total_3=$(($firstnum+$secondnum))
total_4=$(($firstnum-$secondnum))
echo -e "\n The result of $firstnum X $secondnum is ==> $total_1 "
echo -e "\n The resutl of $firstnum / $secondnum is ==> $total_2 "
echo -e "\n The resutl of $firstnum + $secondnum is ==> $total_3 "
echo -e "\n The resutl of $firstnum - $secondnum is ==> $total_4 "

注意,输入的数只能是的整数

统计目录下文件数量和大小

#!/bin/bash
date >/tmp/statistics.txt
today_date=$(date +%Y%m%d)
dir=/tmp/$today_date
dir_total=$([ -e $dir ] && ls -l $dir | awk '/^_/' | wc -l ) #目录使用'/^d/'
dir_size=$([ -e $dir ] && du -s $dir | cut -f 1)
[ -e $dir ] && echo -e "$dir\t\tnumber=$dir_total\tfile_size=$dir_size KB" >>/tmp/statistics.txt

for i in /tmp/directory/*
do
num=$(ls -l $i | awk '/^_/' | wc -l)
size=$(du -s $i |cut -f 1)
echo -e "$i\tnumber=$num\tfile_size=$size KB" >>/tmp/statistics.txt
运行后结果如下:
[root@BACKUP tmp]# cat statistics.txt
一 8月 15 13:32:02 CST 2011
/tmp/20110815 number=0 file_size=8 KB
/tmp/directory/a number=0 file_size=4 KB
/tmp/directory/b number=0 file_size=0 KB

FTP自动登录批量下载/上传文件

从FTP服务器上的/home/date到本地的/home/databackup:

#!/bin/bash
ftp –n<<!
open 192.168.1.171
user user_name user_password
binary
cd /home/date
lcd /home/databackup
prompt
mget * 批量下载
#mput * 批量上传
close
bye
!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux 职场 Shell 休闲