Shell 脚本学习指南读书笔记(长期更新)

关键字:  shell , linux
本文记录自己学习《Shell脚本学习指南》的一些学习笔记,将尽量以简单的例子来说明问题,希望自己能一直坚持下去。

1.使用cut选定字段

ls -l | cut -c 1-10                               选定每行前10个字符

cut -d : -f 1,5 /etc/passwd                以:为界定符,选取passwd文件的第一个和第五个字段

2.使用join连接字段

为了让join输出正确结果,输入的文件必须先进行排序,例子如下:

========================================
#! /bin/bash
# 删除注释并排序数据文件
sed '/^#/d' quotas | sort > quotas.sorted
sed '/^#/d' sales  | sort > sales.sorted
# 以第一个键做结合,将结果产生至标准输出
join quotas.sorted sales.sorted
# 删除缓存数据
# rm quotas.sorted sales.sorted
=========================================

3.使用vi对比2个文件
首先vi一个文件,然后:vsp anotherfile's name, 这样就可以垂直对比着看这两个文件了;:sp anotherfile's name可以横向对比。
两个窗口间切换用Ctrl-w w

4.crontab定时执行任务
*/5 * * * * touch /home/flynewton/a.`date +\%Y-\%m-\%d.\%T`   每5分钟创建一个文件名带有当前时间戳的文件
crontab xxx 执行;
crontab -l查询cron列表; 
crontab -r删除cron任务

5.at命令延迟至特定时间执行
at 21:00 < command-file                                在下午九点执行
at now + 10 minutes < command-file            10分钟后执行
at now + 8hours < command-file                   8小时后执行
at 0400 tomorrow < command-file                明天早上4点执行
at teatime < command-file                            下午16:00执行
atq查看at队列;atrm删除at任务

6.tr命令的使用
语法如下:tr [options] source-char-list replace-char-list

示例:有一个test文件,内容为:aaabbbcccdddefghiii

tr -c "a" "z" < test | cat            得到结果:aaazzzzzzzzzzzzzzzzz,除了a以外,其它字符都用z替换
tr -d "ad" < test | cat               得到结果:bbbcccefghiii,a和d字符被删除
tr -s "ad" < test | cat               得到结果:abbbcccdefghiii,浓缩a和d字符为一个

7.特殊文件:/dev/null与/dev/tty
传送到/dev/null的数据会被系统丢掉,即将数据写入到此文件,则会认为成功完成写入操作,而事实上什么事情也没有做。需要得到命令的退出状态而不是输出时很有用,如:
==========================================
if grep pattern myfile > /dev/null
then
    .... #找到模式
else
    .... #找不到模式
fi
==========================================
将/dev/null写入文件(cat /dev/null > xxx.txt), 将文件结束符写入文件,即清空该文件内容。
/dev/tty,将程序重定向到一个终端,适合于读取人工输入等,例子如下:
 =========================================
#! /bin/bash

printf "Enter your passwd: \n"
stty -echo                   #stty控制终端的各种设置
                             #这里关闭自动打印输入字符的功能
read pass < /dev/tty
printf "Enter again: \n"
read pass2 < /dev/tty
stty echo                    #恢复自动打印输入字符的功能
===========================================

8.简单的执行脚本跟踪
方法一:sh -x your-script-commond
方法二:脚本内设置,set -x打开跟踪,set +x关闭跟踪
9.生成固定大小文件
dd if=/dev/zero of=/home/flynewton/1M.img bs=1K count=1024(生成一个1M的文件,文件名为1M.img)

/dev/zero

From Wikipedia, the free encyclopedia

In Unix-like operating systems/dev/zero is a special file that provides as many null characters (ASCIINULL, 0x00; not ASCII character "digit zero", "0", 0x30) as are read from it. One of the typical uses is to provide a character stream for overwriting information. Another might be to generate a clean file of a certain size. Using mmap to map /dev/zero to RAM is the BSD way of implementing shared memory.

猜你喜欢

转载自flynewton.iteye.com/blog/899704