shell编程常用语句文章分类:操作系统shell基础 #find name #find ../ -name wc* #find modify file time #find ../ -mtime -1 -type f #find mtime modify time atime access time ctime create time + is more than -1 就是1小时以内 +1就是1小时以外的文件 #find ./ -name "[a-z]*" #find ./ -name "[a-f][a-d][a-i]*" #mode #find . -perm 755 #find . -size +100c #find . -name "ec*" -o -name "b*" #find and exec #find . -name "*.c" -exec rm {} \; #find . -name "e*" -exec ls -l {} \; #find . -name "e*" -exec grep "b" {} \; #find minute #find . -mmin -5 #find day + more than - less than #find . -mtime -1 find . -used -2 a="Hello World" b=2 echo "A" is $a echo "B" is ${b}nd a="Hello World" b=2 echo "A" is $a echo "B" is ${b}nd #!/bin/bash case $1 in *.c) echo "this is C file";; *.cpp) echo "this is cpp file";; *.txt) echo "this is txt " esac cat echo.sh>backup_echo cat echo.sh>>backup_echo cat -b back_find dd if=echo.sh of=dd_echo find ./ -name "*ch*" date +"Hour %H.%M" diff echo.sh if.sh dir=/home/wang # 2>/dev/null dont output wrong message if cd "$dir" 2>/dev/null then echo "Now in $dir" else echo "cant go to $dir" fi #!/bin/bash # exe command must add `` if [ -r echo.sh ];then echo "can read" fi #call is ./file2.sh "echo.sh if.sh" add"" to be a one parameter or will be two for element in $1 do if [ -d $element -a -e $element ] then echo "this is directory $element" elif [ -f $element -a -e $element ] then echo "this is file $element" fi done for var in A B C;do echo $var done a=`echo "Hello!"` echo $a b=`ls -l` echo $b echo "$b" #!/bin/bash function xyz { echo "this is function" } xyz grep "echo" echo.sh |wc -l #[] must have space expr must have space var=2 var=`expr $var + 2` if [ $var>=2 ];then echo "success" fi echo $var if grep -q echo echo.sh then echo "File contanins echo" fi #!/bin/bash # string = must have space i=2 if [ $i = 3 ];then echo "success" else echo "wrong" fi #!/bin/bash line=`grep "echo" echo.sh|wc -l` echo $line if [ $line="2" ];then echo "success" else echo "fail" fi if [ `grep "echo" echo.sh|wc -l`="2" ];then echo "success" fi # have problem a=2 b=3 c=4 if [ $b = 3 -a $a>$b ] then echo "right" else echo "wrong" fi if [[ $b > $a&&$c >$b ]] then echo "right2" fi var1=hello var2=world if [ $1 = hello -a $2 = world ] then echo "right" else echo "wrong" fi a=80 let a=$a+20 echo "a is $a" #!/bin/bash ls -R ls -l|cat>$(date +"ls_%d%H%M") var=2 var=`expr $var + 2 ` var=$(($var+2)) echo $var a=123 let a+=1 echo $a let i=5**3 echo $i #if $1 not add "" will have null string problem #more than 9 ${10} if [ -n "${1}" ] then echo $1 fi if [ -n "$2" ] then echo $2 elif [ -z "$2" ] then echo "nullstring" fi #pass parameter in command line echo $1 ps -ef |grep Ultraman read line echo $line File=./echo.sh { read line1 read line2 }<$File echo $line1 echo $line2 { echo "Hello" echo "world" }>redirect.bak cat echo.sh |sort #[[]] is different with [] var=$1 if [[ $1 = z* ]] then echo "tru1" fi if [ $1 == z* ] then echo "true2" fi echo $HOME echo $PATH echo $1 echo $* echo $0 echo $# echo $UID user=`id -nu` echo $user var1=123 var2=243 var3=110 echo "var1=$var1 var2=$var2 var3=$var3" #variable use command must add '' fileFirst=`ls` echo $fileFirst #line wc -l echo.sh #word wc -w echo.sh #character wc -c echo.sh #!/bin/bash i=0 sum=0 while [ $i != "100" ] do i=$(($i+1)) sum=$(($i+$sum)) done echo $i $sum for ((a=1;a<10;a++)) do echo $a done cat /etc/passwd|cut -d":" -f1 a=1 while ((a<100)) do echo $a let a=a+1 ((a++)) done # notice $1 "" or may be null string if [ -n "$1" ] 测试是否空串 then dir=$1 if [ ! -d $dir ] then dir=$PWD echo "wrong directory" fi else dir=$PWD fi echo $dir exec echo "Next will not exe" echo "Hello" find c*|xargs grep "while" for file in `find $PWD -type f` do echo $file done>fileback a=letter letter=z eval c=\$$a echo $c oldIFS=$IFS IFS=: while read name passwd uid gid fullname ignore do echo "$name ($fullname)" done </etc/passwd IFS=$oldIFS #modify file name # why can use *.$1 as a list because directory is a list for filename in $PWD/*.$1 do mv $filename ${filename%$1}$2 done dir=$PWD #is right # $dir/* is /home/wang/* list all file for file in $dir/* do if [[ $file = *.c ]] then filename=${file%.*c} filename=${filename}.cpp mv $file $filename fi done printf "%d\n" 2 #number compare use le lt ge gt eq MAXCOUNT=10 count=1 while [ $count -le $MAXCOUNT ] do number=$RANDOM echo $count echo $number let count=count+1 done #output script name without directory name echo ${0##*/} echo $0 var=$1 echo ${var#*00} # ##lang match #short match stringz=$1 echo ${stringz#a*C} echo ${stringz##a*C} #tail replace stringz=abcABC123ABCabc echo ${stringz%b*c} echo ${stringz%%b*c} var=abc123abcbbc echo ${var/c/D} echo ${var//c/D} echo ${var/%c/D} echo "select your favourite vegetable" select var in apple orange banana do echo $var break done var=`who|cut -d" " -f1` for person in $var do write $person<hello done dir=$PWD # $dir/* is /home/wang/* list all file for file in $dir/* do if [[ $file = *.sh ]] then echo $file fi done inum=`ls -i|grep cwhile.sh|awk '{print $1}'` echo $inum sleep 1000000& echo "have done" stringz="abcde" echo ${#stringz} echo `expr length $stringz` #match stringz=$1 echo `expr match "$stringz" 'a*'` stringz=$1 echo `expr index "$stringz" C` stringz=$1 echo `expr substr $stringz 2 4` 字符串长度 while read line do echo $line echo ${#line} done 字串替代 stringz=abcABC123ABCabc echo ${stringz/abc/xyz} echo ${stringz//abc/xyz} echo ${stringz/#abc/xyz} echo ${stringz/%abc/xyz} time ls -l cat translate|tr a-z A-Z #tr translate rev reverse tac cat tac translate rev translate type -a ls which ls #show the full path wget www.google.cn w3m www.google.cn who|wc -l find .. -name echo.sh|cat echo "1" find .. -name echo.sh|xargs cat echo "2" file *|grep showfile*|cut -d":" -f1|xargs wc -l #limit pass parameter number ls|xargs -n 8 echo #{} is where to replace ls a.cpp|xargs -i cp ./{} a.c dir1=/etc dir2=/bin pushd $dir1 echo "now in `pwd`" pushd $dir2 echo "now in `pwd`" popd echo "noe in `pwd`" popd echo "now in `pwd`" shell理论 反引号的功能是命令替换,将反引号中的字符串做为命令来执行,我们在用shell编程时经常用的到 将系统命令的执行结果赋给一个变量 Shell if比较时候要加空格 if [ $i = 2 ] ;then ... 后台运行命令.一个命令后边跟一个&,将表示在后台运行. Vim ctrl+H ctrl+J ctrl+I ctrl+M 在""中还是会发生变量替换,这被叫做部分引用,或叫弱引用.而在''中就不会发生变量替换,这叫做全引用,也叫强引用. Echo ‘$hello’ • –b 当file存在并且是块文件时返回真 • -c 当file存在并且是字符文件时返回真 • -d 当pathname存在并且是一个目录时返回真 • -e 当pathname指定的文件或目录存在时返回真 • -f 当file存在并且是正规文件时返回真 • -g 当由pathname指定的文件或目录存在并且设置了SGID位时返回为真 • -h 当file存在并且是符号链接文件时返回真,该选项在一些老系统上无效 • -k 当由pathname指定的文件或目录存在并且设置了“粘滞”位时返回真 • -p 当file存在并且是命令管道时返回为真 • -r 当由pathname指定的文件或目录存在并且可读时返回为真 • -s 当file存在文件大小大于0时返回真 • -u 当由pathname指定的文件或目录存在并且设置了SUID位时返回真 • -w 当由pathname指定的文件或目录存在并且可执行时返回真。一个目录为了它的内容被访问必然是可执行的。 • -o 当由pathname指定的文件或目录存在并且被子当前进程的有效用户ID所指定的用户拥有时返回真。 UNIX Shell 里面比较字符写法: • -eq 等于 • -ne 不等于 • -gt 大于 • -lt 小于 • -le 小于等于 • -ge 大于等于 • -z 空串 • = 两个字符相等 • != 两个字符不等 • -n 非空串 “” ‘’ \用来禁止转义 如果点放在文件名的开头的话, 那么这个文件将会成为"隐藏"文件, 并且ls命令将不会正常的显示出这个文件. shell进阶 #!/bin/bash #read a file time file=$1 timefile=./timelog function usage { echo "wrong use function" exit 1 } function while_read { cat $file | while read Line do echo $Line done } function while_read_bottom { while read Line do echo $Line done<$file } function while_line { cat $file|while line Line do echo $Line done } function while_line_bottom { while line Line do echo $Line done<$file } function line_tidai { cat $file|while Line=`line` do echo $Line done } if (($#!=1)) then usage fi if [ -f $timefile ] then rm $timefile fi touch $timefile echo -e "\nwhile_read\n" time while_read>>$timefile echo -e "\nwhile_read_bottom\n" time while_read_bottom>>$timefile echo -e "\nwhile_line\n" time while_line>>$timefile echo -e "\nwhile_line_bottom\n" time while_line_bottom>>$timefile echo -e "\nline_tidai\n" time line_tidai>>$timefile #!/bin/bash cat /etc/passwd|cut -d":" -f 1,3 name=wang echo "$name" echo '$name' echo "\\hello" echo '\\hello' echo "today is `date`" echo 'today is `date`' #!/bin/bash df -h|tail -n +2|grep -v "/dev/sda[^3-9]"|grep -v "none" ""% `` \会进行变量替换 '' 直接输出 -h human readerable -k kb df -k df -h tail -n +2 打印从首行开始的第二行 grep -v 输出不匹配的行 ctrl+alt +F7 是图形化界面 Linux 远程需要sudo apt-get install openssh-sever sudo apt-get install vnc4server 注意防火墙关掉 pstree 查看进程 deb包默认下载到 /var/cache/apt/archives grep 注意正则表达式 有些 '' ""注意转义和* $? 状态码 $# 参数数目 $! PID 终端浏览器w3m 正则表达式 \{2\} 表示重复2次 \{2,\} 表示重复2次以上 #!/bin/bash #\ 表示一个命令可以换行而接续上一行的命令 用于长命令 #sed s 替换 s/ / /g g表示替换所有 FSMAX=15 WorkFile=./df.work OutFile=./df.out if [ -f $WorkFile ] then rm $WorkFile fi if [ -f $OutFile ] then rm $OutFile fi touch $WorkFile touch $OutFile df -h|tail -n +2|grep -v "/dev/sda[0-1]"|grep -v "none"| awk '{print $1,$5,$6}'>>df.work while read fsdevice fsvalue fsmount do # fsvalue=`echo $fsvalue|sed s/\%//g` #两种方式都可以使用 sed 和匹配法 注意 转义 \% fsvalue=${fsvalue%\%} if ((fsvalue>FSMAX)) 注意使用2个括号C的方式 then echo "$fsdevice $fsvalue $fsmount">>df.out fi done<$WorkFile #-s 如果文件存在 if [ -s $OutFile ] then cat $OutFile fi #!/bin/bash #\ 表示一个命令可以换行而接续上一行的命令 用于长命令 #sed s 替换 s/ / /g g表示替换所有 FSMAX=15 WorkFile=./df.work OutFile=./df.out ExceptionFile=./fs_exception DataException=./data_exception if [ -f $DataException ] then rm $DataException fi if [ -f $WorkFile ] then rm $WorkFile fi if [ -f $OutFile ] then rm $OutFile fi touch $WorkFile touch $OutFile touch $DataException df -h|tail -n +2|grep -v "/dev/sda[0-1]"|grep -v "none"| awk '{print $1,$5,$6}'>>df.work NowMax=$FSMAX #^表示开头 $表示结尾 去掉#注释行 和空行 cat $ExceptionFile|grep -v "^#"|sed /^$/d>$DataException while read fsdevice fsvalue fsmount do # fsvalue=`echo $fsvalue|sed s/\%//g` #两种方式都可以使用 sed 和匹配法 注意 转义 \% fsvalue=${fsvalue%\%} #查找是否存在Exception中,是则比较,将值设置为NowMax if [ -s $DataException ] then while read ExceptionMount NewMax do #字符串比较必须加空格 =等于号之间 否则错误 if [[ $fsmount = $ExceptionMount ]] then NowMax=${NewMax%\%} break fi done<$DataException fi if ((fsvalue>NowMax)) then echo "$fsdevice $fsvalue $fsmount">>df.out #NowMax设置回来 NowMax=$FSMAX fi done<$WorkFile #-s 如果文件存在 if [ -s $OutFile ] then cat $OutFile fi #!/bin/bash #this file is use to mk a big file #echo -e "\c" 代表不换行 Line_Length=80 Total_Length=$1 OutFile=./bigfile Line_Count=0 Char=X function usage { echo "usage error" } if (($#!=1)) then usage exit 1 fi if [ -f $OutFile ] then rm -f $OutFile fi touch $OutFile while ((Line_Count<Total_Length)) do Char_Count=0 while((Char_Count<Line_Length)) do echo -e "${Char}\c">>$OutFile ((Char_Count++)) done ((Line_Count=Line_Count+1)) # echo $Line_Count echo>>$OutFile done #cat $OutFile #!/bin/bash #& is back run #$! is the pid while true do echo -e ".\c" sleep 3 done& Old_PID=$! ./mk_bigfile.sh 1500 kill $Old_PID #!/bin/bash TCount=0 interval=3 while true do ((Tcount=Tcount+1)) case $Tcount in "1") echo -e "-\b\c" sleep $interval ;; "2") echo -e '\\'"\b\c" sleep $interval ;; "3") echo -e "|\b\c" sleep $interval ;; "4") echo -e "/\b\c" sleep $interval ;; *) Tcount=0 ;; esac done& Old_PID=$! ./mk_bigfile.sh 1000 kill $Old_PID #!/bin/bash echo "参数个数"$# echo $! echo "状态码:"$? #!/bin/bash #cut -d ":" -f 1 /etc/passwd #cut -c 列出第几个字符 #cut -c 1 /etc/passwd #od 以八进制显示 #od command.sh #16进制显示 #od -x command.sh # cp -p 保存原来的拥有者组和使用权限 #mkdir -p 自动创建其中不存在的目录 #mkdir -m 744 home #touch file 把文件访问时间设定为现在 #tee 显示管道里面的内容 # -n 只取样1次 # top -n 1 |grep root # -d delay #top -d 1 # kill -l 显示所有信号 #nice 数字越小优先级越高 renice #nice -n -10 vi hello #!/bin/bash tail -n +2 sortfile tail -n -1 sortfile #翻转 tac sortfile #翻译 tr a-z A-Z<sortfile cat sortfile|tr a-z A-Z #!/bin/bash #-n 表示每次只接受一个参数 find ../../ -type f |xargs -n 1 grep java #xargs 可以把文件内部的内容输出来 而不只是输出管道到文件名 #find ./ -name uniqfile |xargs grep java #!/bin/bash #删除#开头的行 #sed '/^#/d' sedfile #sed 's/^#/$/' sedfile # sed 's/^#/$/g' sedfile # 替换2个以上空格为一个空格 ,逗号不要忘了 表示2个或者多个 #sed 's/ \{2,\}/ /g' sedfile #删除有空格的行 #sed '/ /d' sedfile #将4-6 行的a换成A #sed '4,6s/a/A/g' sedfile #去掉空行 #grep -v '^$' sedfile #计算空行 grep -c '^$' sedfile #!/bin/bash #k用于第几个字段排序 t用于一行的分割字符 sort -k 1 -t "," sortfile echo echo sort -k 2 -t "," sortfile echo echo sort sortfile echo echo sort -k 2 sortfile #!/bin/bash #uniq -u 只显示不重复的行 -d 只显示重复的 #uniq 只删除相邻行重复的 所以要与sort 一起用 sort uniqfile | uniq sort uniqfile |uniq -u sort uniqfile |uniq -d # -c 计算重复次数 sort uniqfile |uniq -c |sort sort uniqfile |uniq -c |sort -k 2 grep -v 显示不匹配的 grep -E 扩展 注意E 大写 grep -i 忽略大小写 grep -c 显示匹配的行数 grep -o 只显示匹配的字符串 #!/bin/bash #" " '' grep #grep NW datafile #grep '^n' datafile # ^ 开头 $ 结尾 #grep '4$' datafile #注意引号 否则空格会导致 文件分割 #grep "TB Savage" datafile #\. 转义. #grep '5\..' datafile #grep "^[we]" datafile #打印所有包含非数字的行 #grep '[^0-9]' datafile #打印包含两个大写字符一个空格加上一个大写字符的 #grep '[A-Z][A-Z] [A-Z]' datafile #grep 'ss* ' datafile #打印至少9个小写连续字符的 #grep '[a-z]\{9\}' datafile #匹配至少5个a \{n\}至少匹配n个字母 #grep 'a\{5\}' datafile # \< \>界定一个单词的开头或者结尾 #grep '\<north' datafile #grep '\<north\>' datafile # \b 也可以界定单词的开头或者结尾 #grep '\bnorth\b' datafile #grep '\<[a-z].*n' datafile # # # #grep -E E注意大写 #grep -E 'NW|WE' datafile # * 0个或者多个 + 1个或者多个 ?0个或者1个 .一个 #匹配一个或者多个3 #grep -E '3+' datafile #grep -E '2\.?[0-9]' datafile #()表示一个词组 这里1个或者多个no #grep -E '(no)+' datafile #[^0-9]不在0-9之间 -E 不需要 \{\} #grep -E '\.[0-9]{2}[^0-9]' datafile #只显示匹配的行数 # grep -c '\bnorth' datafile #只显示字符串 #grep -o '\bnorth' datafile #!/bin/bash grep "file.*" file.* grep file.* file.* #!/bin/bash #找出非空行 #grep '.' grep3file #找出有连续5个字母的行 #grep '.....' grep3file #找出含有. 的行 #grep '\.' grep3file #找出有2个连续数字的行 #grep '[0-9]\{2\}' grep3file #找出有3-5个数字的单词 #grep '\b[0-9]\{2,5\}\b' grep3file #与上一个的区别 #grep '[0-9]\{2,5\}' grep3file #找电话号码格式 grep '[0-9]\{3\}-[0-9]\{2\}-[0-9]\{4\}' grep3file |
|