Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3017627
  • 博文数量: 535
  • 博客积分: 15788
  • 博客等级: 上将
  • 技术积分: 6507
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-07 09:11
文章分类

全部博文(535)

文章存档

2016年(1)

2015年(1)

2014年(10)

2013年(26)

2012年(43)

2011年(86)

2010年(76)

2009年(136)

2008年(97)

2007年(59)

分类: LINUX

2008-08-14 10:38:29

20120731:
移动最近7天修改的前10个文件到tmp目录
 ls -rt $(find . -type f  -mtime +7)|head -10|xargs -i  mv {}  /tmp/

20120530:关联数组
关联数组在 bash shell 4.0 及以上版本获得支持。
声明一个关联数组首先需要用 declare 命令的 -A 选项来声明该数组的名字,如 declare -A myarr ,如:
declare -A myarr
myarr=([flower]=rose [fruit]=appale)
echo ${myarr[flower]}
echo ${myarr[fruit]}

20120529: 参数替换:
如果在命令行中指定参数,则赋值,否则为默认值,正确的写法是

  1. date=${1:-`date -d "1 days ago" +%Y%m%d`}
将第一个参数赋值,也可以用下面的方法:

  1. manual_date=$1
  2. date=${manual_date:=`date -d "1 days ago" +%Y%m%d`}

下面的方法会报错

  1. date=${1:=`date -d "1 days ago" +%Y%m%d`}
 $1: cannot assign in this way

man bash中可以看到:
       ${parameter:-word}
              Use Default Values.  If parameter is unset or null, the expansion of word  is  substituted.   Otherwise,
              the value of parameter is substituted.
       ${parameter:=word}
              Assign  Default  Values.  If parameter is unset or null, the expansion of word is assigned to parameter.
              The value of parameter is then substituted.  Positional parameters and special  parameters  may  not  be
              assigned to in this way.


$! 后台运行的PID

  1. sleep 200 &
  2. echo 1 $!
  3. sleep 200 &
  4. echo 2 $!

变量检查
注意: 冒号后面有空格
  1. : ${user?} ${pass?}
  2. 或者
  3. : ${user?"error message"}

  1. : ${1?"no args 1"}


20101117:双括号运算符语法: 
((表达式1,表达式2…)) 
特点: 
1、在双括号结构中,所有表达式可以像c语言一样,如:a++,b--等。 
2、在双括号结构中,所有变量不加入:“$”符号前缀。 
3、双括号可以进行逻辑运算,四则运算 
4、双括号结构 扩展了for,while,if条件测试运算 
5、支持多个表达式运算,各个表达式之间用“,”分开 
测试:

a=0
function f_test(){
        ((a++))
        echo "now a=$a"

        if [[ "$a" -gt "7" ]];then
                echo "now $a -gt 7,exit"
                exit
        else
                f_test
        fi
}

f_test

20100823:shell的substr实现:expr substr 20100823 1 4
20100819:批量更改带空格的文件:ls access_20100819-\ *|while read a;do b=`echo $a|tr -d ' '`;echo $a $b;done或者用perl20100716:关于给脚本传递参数:manual_date=$1 date_1hour_ago=${manual_date:=`date -d "1 hour ago" +"%Y%m%d%H"`}如果传递了参数,则date_1hour_ago为$1,如果没有传递参数,则date_1hour_ago=`date -d "1 hour ago" +"%Y%m%d%H"`
20090811:seq如:生成1到100的数: seq 100seq -s "-" 0 2 100到10,每次递加2,以-为分割符。详细查看man seq
090728:eval 间接引用变量间接引用的实际用处是什么? 它提供了Bash具有C中一点指针的功能eval就是先将后面的参数执行一遍,将必要的置换都做了,再来执行命令。举个例子: 
MYFILE="cat myfile" 
echo $MYFILE  # output: cat myfile 
eval $MYFILE  # output: contents of myfile 

090728:双括号((...))结构允许算术计算和求值. 它最简单的形式a=$(( 5 + 3 )) 会把变量"a"的值设置成"5 + 3"或8. 但是,在Bash中双括号结构也是遵循C风格的变量操作的一种机制.如:for ((a=0;a<30;a++))doecho $adone或 for ((a=0;a<10;a++));do echo $a ;done
090716:pgrep -f 'grep ck.php'等效于ps -ef|grep 'grep ck.php' 对应的还有pkill,更多用法详细查看man
090715:在awk中调用shell的变量:问题:$parent_pid=2345child_pid=`ps -ef |awk "$3==$parent_pid { print $2}"`当域3等于2345时,将域2的值赋给child_pid,这样写是不行的,$2和$3都被认为是shell的变量,所以需要更改为:all_child_pid=$(ps -ef |awk -v pid="$parent_pid" '$3==pid { print $2}')即,使用-v参数引入shell的变量$parent_pid到awk里,同时使用单引号’这样就不会将$2和$3当成是shell的变量了,

关于sed 插入TAB,TAB符在shell上是這樣輸入的:ctrl+v+i

在shell脚本开头添加  set -x 输出调试信息

关于date输出日期
date显示昨天的日期 date -d yesterday +%Y-%m-%d
date显示昨天的昨天的昨天的时期
date -d yesterday+yesterday+yesterday +%Y-%m-%d

在使用join之前,文件应该是被分类过的,即被sort的,否则,结果不正确。

1.sed查找匹配行,对其行首和行尾增加字符
sed '/import/{s/^/#/;s/$/ test/}'
查找带有import的行,行首增加#行尾增加 test。答案蛮经典的。

sed 打印匹配的行号 = 显示打印的行号
sed -n  '/2008-12-17/=' /usr/local/apache/errorlog|sed -n '1p'

2. 删除某个字符
tr -d
如 cat error_log |awk '/authentication failure/ {print $8}'|tr -d "]"

3 使用 []做条件测试时,如果测试的对象是变量时要注意给变量加双引号“”
如 if  [ -z "$exist" ] ;then

4 使用sed,awk等工具时,如果里面包含变量,应适用双引号“”而不能用单引号‘’
如 sed "/^[1-9]/{s/$/ $i/}" $confdir  > /tmp/denylist 
其中 我的$i 是个变量

sed "/^[1-9]/{s/$/ $i/}" $confdir  > /tmp/denylist 
匹配以数字开头的行,在行的末尾添加$i。原理是用s替换命令,将行尾替换为 空格+$i

5 使用sed,替换变量,变量中含有特殊符号,如 /,出现错误 ,如 
/bin/sed  "27 s/\/tmp\/test0/$src" code.c.bak >code.c
变量为/tmp2/test2,使用上面的命令会出错,解决办法如下
/bin/sed  "27 s /tmp/test0 $src " code.c.bak >code.c

在这插一段:
关于ssh 连接到远程服务器,执行sed命令报错的问题,如:
ssh   root@174.129.23.150 sed  '/Smtphost-here/a\' /opt/123
sed: can't read Host/: No such file or directory
通过 ssh -v 的deubg,发现,发送过去的命令变成了:

debug1: Sending command: sed /Smtphost-here/a\\ /home/optin/inject_2414/config-sample.xml
把‘’单引号丢了,通过红色的地方发现需要使用\来取消转意,那么就OK了
ssh   root@174.129.23.150 sed  \'/Smtphost-here/a\\' /opt/123
OK,问题解决了


6.awk 不打印某行
方法1 awk '{$2="";$3="";print}' file        #实际上是把2,3域换成了空
方法2 awk '{for (i=1;i<=NF;i++) if(i!=3) printf("%s ",$i)}' file

7.here string 可以被认为是here document的一种定制形式. 除了COMMAND <<<$WORD 就什么都没有了, $WORD将被扩展并且被送入COMMAND的stdin中.
如:[jason@uranus 7]$ wc -l <<
    5514 db.21cn
    4876 db.china
    4043 db.citiz
   40739 db.netease
   46441 db.o
   85399 db.sina
    1690 db.sohu
    2085 db.tom
  381574 总计


6 awk ' 模式 {动作}'
awk的“与”“或”模式
如 awk'$0~/(green|yellow)/' gra.txt
为一域号匹配正则表达式,使用符号~后紧跟正则表达式。

复合语句 && || !
awk '{if ($1=="123" && $4`/tre/) print$7}' 
注意,if是放在动作里的

for 循环
awk  '{for (i=1;i<=NF;i++) print $i}'

awk 打印前几个域
awk -F "/" '{NF=NF-1;OFS="/";print $0}'
用于取一个文件所在的目录


7 grep的“与”“或”模式
grep 命令加-E参数,这一扩展允许使用扩展模式匹配。
如grep -E '219|231' data.txt


8 break 和 continue
在shell编程中,循环语句中都是有done作为循环的结束。
break语句可以跳出循环,把控制直接转移到done之后的内容。
continue语句把控制直接传递到done语句,但是循环并不终止而是继续执行。
#! /bin/bash

for index in 1 2 3 4 5 6 7 8 9 10
    do
      if [ $index -le 3 ]; then
         echo "continue"
         continue
      fi

      echo $index

    if [ $index -ge 8 ]; then
         echo "break"
         break
    fi
   done
运行结果:
continue
continue
continue
4
5
6
7
8
break

9 $variable实际上只是${variable}的简单的简写形式。在某些场合使用$variable形式会引起错误,这时你可能需要使用${variable}的形式

把变量引起来会保留空白字符.如 
a=`ls -l`         # 把'ls -l'命令的结果赋给变量'a'
echo $a           # 如果没有引号,则会删除多余tab键和空白符
echo
echo "$a"         # 加了双引号,则能够原样保留空白符

10 if和then都是关键字.关键字(或命令)开始一个语句,如果在同一行开始另一个新语句时,前面一个语句必须用分号(;)结束。

11 if test condition-true结构是精确等同于if [ condition-true ].如果用[ condition-true ]结构,左方括[ , 是一个调用test命令的标识。右方括]在一个if/test中封闭左方括[,但它不是必须的,不过新一些的Bash版本会要求有。
在[[和]]之间的所有的字符都不会被文件扩展或是标记分割,但是会有参数引用和命令替换。
用[[ ... ]]测试结构比用[ ... ]更能防止脚本里的许多逻辑错误。比如说,&&,||,<和>操作符能在一个[[]]测试里通过,但在[]结构会发生错误。

12 混合比较 
-a 逻辑与  -o 逻辑或
它们和Bash中用于双方括号结构的比较操作符&&和||很相似。
   1 [[ condition1 && condition2 ]]
-o和-a操作符和test命令或单方括号一起使用。
   1 if [ "$exp1" -a "$exp2" ]

13 位置参数
$0, $1, $2,等等 位置参数由命令行传给脚本或传给一个函数,或设置(set)给一个变量.
$# 命令行参数或者是位置参数的数量
$* 所有的位置参数都被当成单个单元。"$*"必须被引号引起来。

14 
$$ 脚本本身的进程PID。$$变量常被用于脚本中生成一个"唯一的"临时文件名. 这通常比调用mktemp还要简单。

15 操作字符串
取字符串长度:${#string}、expr length $string、expr "$string" : '.*' ,三种方法都可以。

16 子串移动
${string#substring}
从$string左边开始,剥去最短匹配$substring子串.
${string##substring}
从$string左边开始,剥去最长匹配$substring子串.

   1 stringZ=abcABC123ABCabc
   2 #       |----|
   3 #       |----------|
   4 
   5 echo ${stringZ#a*C}      # 123ABCabc
   6 # 剥去匹配'a'到'C'之间最短的字符串.
   7 
   8 echo ${stringZ##a*C}     # abc
   9 # 剥去匹配'a'到'C'之间最长的字符串.

${string%substring}
从$string结尾开始,剥去最短匹配$substring子串。
${string%%substring}
从$string结尾开始,剥去最长匹配$substring子串。


17 参数替换
${parameter}和$parameter是相同的,都是表示变量parameter的值。在一些环境中,使用${parameter}比较不会引起误解.

${parameter-default}, ${parameter:-default}
如果变量没有被设置,使用默认值。${parameter-default}和${parameter:-default}几乎是相等的。它们之间的差别是:当一个参数已被声明,但是值是NULL的时候两者不同.
 echo ${username-`whoami`}
 # 如果变量$username还没有被设置,则把命令`whoami`的结果赋给该变量.
例  BACKUPFILE=backup-$(date +%m-%d-%Y)
     #                 Embeds date in backup filename.
     #                 Thanks, Joshua Tschida, for the idea.
     archive=${1:-$BACKUPFILE}
如果使用该脚本时没有指定参数,默认参数为$BACKUPFILE

18 awk中使用date命令
awk '{print '"$(date +"%Y%m%d")"',$1,$5,$6,$7,$8}'
awk '{print system("date") , $1,$5,$6,$7,$8}'

19 about job and process

It is all too easy to confuse jobs and processes. Certain , such as killdisown, and wait accept either a job number or a process number as an argument. The fgbg and jobs commands accept only a job number.

bash$ sleep 100 & [1] 1384 bash $ jobs [1]+ Running sleep 100 &

"1" is the job number (jobs are maintained by the current shell), and "1384" is the process number (processes are maintained by the system). To kill this job/process, either a kill %1 or a kill 1384 works.


20 wait

Stop script execution until all jobs running in background have terminated, or until the job number or process ID specified as an option terminates. Returns the exit status of waited-for command.

You may use the wait command to prevent a script from exiting before a background job finishes executing (this would create a dreaded orphan process).

1 #!/bin/bash 2  3 ROOT_UID=0 # Only users with $UID 0 have root privileges. 4 E_NOTROOT=65 5 E_NOPARAMS=66 6  7 if [ "$UID" -ne "$ROOT_UID" ] 8 then 9  echo "Must be root to run this script." 10  # "Run along kid, it's past your bedtime." 11  exit $E_NOTROOT 12 fi 13  14 if [ -z "$1" ] 15 then 16  echo "Usage: `basename $0` find-string" 17  exit $E_NOPARAMS 18 fi 19  20  21 echo "Updating 'locate' database..." 22 echo "This may take a while." 23 updatedb /usr & # Must be run as root. 24  25 wait 26 # Don't run the rest of the script until 'updatedb' finished. 27 # You want the the database updated before looking up the file name. 28  29 locate $1 30  31 # Without the 'wait' command, in the worse case scenario, 32 #+ the script would exit while 'updatedb' was still running, 33 #+ leaving it as an orphan process. 34  35 exit 0

Optionally, wait can take a job identifier as an argument, for example, wait%1 or wait $PPID。

21  ls
      using the -R, recursive optionls provides a tree-like listing of a directory structure. Other useful options are -S, sort listing by file size, -t, sort by file modification time, and -i, show file inodes


22  cat
The -n option to cat inserts consecutive numbers before all lines of the target file。The -b option numbers only the non-blank lines. The -v option echoes nonprintable characters, using ^ notation. The -s option squeezes multiple consecutive blank lines into a single blank line.

tac, is the inverse of cat, listing a file backwards from its end.

23  mkdir
mkdir -p project/programs/December creates the named directory. The -p option automatically creates any necessary parent directories.

24 chattr
chattr +i filename marks the file as immutable. The file cannot be modified, linked to, or deleted , not even by root. This file attribute can be set or removed only by root. In a similar fashion, the a option marks the file as append only.


24 ln
The ln command is most often used with the -s, symbolic or "soft" link flag. Advantages of using the -s flag are that it permits linking across file systems or to directories.(since it is just a reference to a file name, not to actual data)

25  find
-exec COMMAND \;
Carries out COMMAND on each file that find matches. The command sequence terminates with ;在每一个find 匹配到的文件执行 COMMAND 命令. 命令序列以 ; 结束
If COMMAND contains {}, then find substitutes the full path name of the selected file for "{}". 如果 COMMAND 中包含 {}, 那么 find 命令将会用所有匹配文件的路径名来替换 "{}" .


26 tail
To list a specific line of a text file,  the output of head to tail -1. For example head -8 database.txt | tail -1 lists the 8th line of the file database.txt.

To set a variable to a given block of a text file:

1 var=$(head -$m $filename | tail -$n) 2  3 # filename = name of file 4 # m = from beginning of file, number of lines to end of block 5 # n = number of lines to set variable to (trim from end of block)


27 grep
A multi-purpose file search tool that uses Regular Expressions. It was originally a command/filter in the venerable ed line editor: g/re/p -- global - regular expression - print.

grep pattern [file...]

The -i option causes a case-insensitive search.不区分大小写
The -w option matches only whole words.完全匹配
The -l option lists only the files in which matches were found, but not the matching lines.列出文件名
The -r (recursive) option searches files in the current working directory and all subdirectories below it.递归
The -n option lists the matching lines, together with line numbers.列出匹配的行号
The -v (or --invert-match) option filters out matches. 过滤匹配的
The -c (--count) option gives a numerical count of matches, rather than actually listing the matches.给出匹配的数量。

When invoked with more than one target file given, grep specifies which file contains matches.

bash$ grep Linux osinfo.txt misc.txt osinfo.txt:This is a file containing information about Linux. osinfo.txt:The GPL governs the distribution of the Linux operating system. misc.txt:The Linux operating system is steadily gaining in popularity.

Tip

To force grep to show the filename when searching only one target file, simply give /dev/null as the second file.

bash$ grep Linux osinfo.txt /dev/null osinfo.txt:This is a file containing information about Linux. osinfo.txt:The GPL governs the distribution of the Linux operating system.

egrep - extended grep - is the same as grep -E. This uses a somewhat different, extended set of , which can make the search a bit more flexible.

fgrep - fast grep - is the same as grep -F. It does a literal string search (no Regular Expressions), which usually speeds things up a bit.

To search compressed files, use zgrepzegrep, or zfgrep. These also work on non-compressed files, though slower than plain grepegrepfgrep. They are handy for searching through a mixed set of files, some compressed, some not.

To search  files, use bzgrep.


28 tr 

character translation filter。字符替换

 tr "a-z" "A-Z"

The -d option deletes a range of characters.

The --squeeze-repeats (or -s) option deletes all but the first instance of a string of consecutive characters. This option is useful for removing excess whitespace.

The -c "complement" option inverts the character set to match. With this option, tr acts only upon those characters not matching the specified set.

bash$ echo "acfdeb123" | tr -c b-d + +c+d+b++++

29 jotseq

These utilities emit a sequence of integers, with a user-selected increment.

The normal separator character between each integer is a newline, but this can be changed with the -s option.

bash$ seq 5 1 2 3 4 5 bash$ seq -s : 5 1:2:3:4:5

Both jot and seq come in handy in a .

Example 12-49. Using seq to generate loop arguments

1 #!/bin/bash 2 # Using "seq" 3  4 echo 5  6 for a in `seq 80` # or for a in $( seq 80 ) 7 # Same as for a in 1 2 3 4 5 ... 80 (saves much typing!). 8 # May also use 'jot' (if present on system). 9 do 10  echo -n "$a " 11 done # 1 2 3 4 5 ... 80


30 yes 

In its default behavior the yes command feeds a continuous string of the character y followed by a line feed to stdout 。

yes | rm -r dirname has same effect as rm -rf dirname (careful!).


31 mcookie

This command generates a "magic cookie", a 128-bit (32-character) pseudorandom hexadecimal number, normally used as an authorization "signature" by the X server. This also available for use in a script as a "quick 'n dirty" random number.

1 random000=$(mcookie)

32 Moduleslsmod

List installed kernel modules.

bash$ lsmod Module Size Used by autofs 9456 2 (autoclean) opl3 11376 0 serial_cs 5456 0 (unused) sb 34752 0 uart401 6384 0 [sb] sound 58368 0 [opl3 sb uart401] soundlow 464 0 [sound] soundcore 2800 6 [sb sound] ds 6448 2 [serial_cs] i82365 22928 2 pcmcia_core 45984 0 [serial_cs ds i82365]

Note

Doing a cat /proc/modules gives the same information.

insmod

Force installation of a kernel module (use modprobe instead, when possible). Must be invoked as root.

rmmod

Force unloading of a kernel module. Must be invoked as root.

modprobe

Module loader that is normally invoked automatically in a startup script. Must be invoked as root.




学习 《sed & awk 》第二版 

1.sed遍历文件,每次一行,这样每一行都成为当前行,而且每一行都应用这个命令,结果是sed对文件中的每一行应用了没有地址的命令。
2.sed命令是隐形的全局命令。
3.在sed和awk中,每个指令都包含两个部分:模式和过程。模式是由斜杠(/)分隔的正则表达式。过程指定一个或多个将被执行的动作。
4.sed 's/ma/materh/’ list
s:替换命令
sed使用单引号阻止shell解释指令中的特殊字符或空格。
5.有3种方式可以指定命令行上的多重指令:
1)用分号分隔指令。
sed 's/MA/mathe/;s/pa/path/' list
2)在每个指令前放置-e
sed -e 's/MA/mathe/' -e 's/pa/path/' list
3)使用bash的分行指令
sed '
>s/MA/mathe/
>s/pa/path/' list

6.sed的默认操作是输出每个输入行。-n选项可以阻止自动输出。当指定该选项时,每个要生成输出的指令都必须包含打印命令p。
sed -n -e 's/MA/message/p' list
7.awk使用和sed相同的方式输入多重指令。
1)用分号分隔指令。
2)在每个指令前放置-e
3)使用bash的分行指令

8.sed首先将整个sed脚本应用于第一个输入行,然后再读取第二个输入行并对其应用整个脚本。

9.sed一次一行的设计的一个有点是sed在读取非常庞大的文件时不会出现问题。屏幕编辑程序必须将整个文件读入内存,这将会产生内存移除或者

在处理庞大的文件时速度非常慢。

10.在vi中除非你告诉它对哪一行操作,否则它什么事情也不做;而sed将处理每一行,除非你告诉它不要做。

11.sed命令可以指定零个、一个或两个地址。每个地址都是一个描述模式、行号或者行寻址符号的正则表达式。
如果没有指定地址,那么命令将应用于每一行。
如果只有一个地址,那么命令应用于与这个地址匹配的任意行。
如果指定了由逗号分隔的两个地址,那么命令应用于匹配第一个地址的第一行和它后面的行,直到匹配第二个地址的行。
如:sed -n '/2008-12-15/,2008-12-16/p' catalina.cout
如果地址后面跟有感叹号(!),那么命令就应用于不匹配该地址的所有的行。


阅读(1714) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~