设为首页 收藏本站
查看: 1850|回复: 0

Bash 笔记

[复制链接]
累计签到:161 天
连续签到:1 天
发表于 2016-11-16 16:35:52 | 显示全部楼层 |阅读模式
Sed:
p: Print text.
s: Search and replace text.
-n: Silent mode.
-i: 修改原数据

*************************************************************
example:
        This is the first line of an example text.
        It is a text with erors.
        Lots of erors.
        So much erors, all these erors are making me sick.
        This is a line not containing any errors.
        This is the last line.
*************************************************************
        sed '/erors/p' example #没有-n 选项会将example内容全部输出,同时将含有erors的行重复输出
        sed  -n '/erors/p' example
        sed '/erors/d' example #不显示含有erors的行
        sed '2,4d' example
        sed '3,$d' example#删除3行至结尾的所有行
        sed -n '/a text/,/This/p' example #只显示包含a text的,与包含含有This的行,及其中间的所有行
        sed        's/erors/errors/' example
        sed  's/erors/errors/g' example
        sed  's/^/#/' example(Vim:1,3s/^/#/, 1,3s/^#//)
        sed  's/$/EOL/' example(Vim:1,3s/$/EOF/)       
        sed  -e 's/erors/errors/g' -e 's/last/final/g' example   #Multiple find and replace commands are separated with individual -e options


AWK:
        ls -l | awk '{ print $5 $9 }'
        ls -ldh * |grep -v total |         awk '{ print "Size is " $5 "Bytes for " $9}'
        df -h |sort -rnk 5|head -3 |awk '{print "Partition" $6 "\t: " $5 "full!"}'       
        df -h | awk '/dev\/sd/ { print $6 "\t:" $5 }'
        ls -l | awk '/\<(a|x).*\.conf$/ { print $9 }'
        ls -l |awk 'BEGIN { print "Files found :\n"} /\<[a|x].*\.conf$/ { print $9 }'
        ls -l | awk '/\<[a|x].*\.conf$ { print $9 } END { print "Can I do anything else for you?"}'
        awk 'BEGIN { FS=":"} { print $1 "\t" $5 }'        /etc/passwd
        cat printnames.awk
        BEGIN { FS=":" }
        { print $1 "\t" $5 }
        awk -f printnames.awk /etc/passwd
        awk '{ print $1 $2 }' test
        awk '{ print $1, $2 }' test
        OFS:output separator
        ORS:output record separator
        awk 'BEGIN { OFS=";" ; ORS="\n------>\n" } { print $1, $2 }' test
        awk 'BEGIN { OFS="-"; ORS="\n-->done\n"} { print "Record number " NR "\t" $1,$2 } END { print "Number of records processed:" NR }'
        awk '{ total=total+$5 } { print "send bill for " $5 " dollar to " $4 } \
        END { print "----------------------------\nTotal revenue:" total }' \
        grep awk /etc/init.d/*


Grep:
        Regular expression operators:
        .                Matches any single character.
        ?                The preceding item is optional and will be matched, at most, once.
        *                The preceding item will be matched zero or more times.
        +                The preceding item will be matched one or more times.
        {N}                The preceding item is matched exactly N times.
        {N,}        The preceding item is matched N or more times.
        {N,M}        The preceding item is matched at least N times, but not more than M times.
        ?                represents the range if it's not first or last in a list or the ending point of a range in a list.
        ^                Matches the empty string at the beginning of a line; also represents the characters not in the
                        range of a list.
        $                Matches the empty string at the end of a line.
        \b                Matches the empty string at the edge of a word.
        \B                Matches the empty string provided it's not at the edge of a word.
        \<                Match the empty string at the beginning of word.
        \>                Match the empty string at the end of word.
******************************************************************************
        grep root /etc/passwd
        grep -n root /etc/passwd
        grep -v bash /etc/passwd | grep -v nologin
        grep -c false /etc/passwd
        grep -i ps ~/.bash* |grep -v history
        grep ^root /etc/passwd(getent passwd |grep ^root)
        grep :$ /etc/passwd
        grep export ~/.bashrc |grep '<PATH'
        grep -w / /etc/fstab
        grep [yf] /etc/group(getent group | grep [yf])
        ls *[1-9].xml
*****************************************************************************
Wildcards
        .: for a sigle character match
        the asterisk (*) and the question mark (?) match any string or any single character
        grep '\<c...h\>' /usr/share/dict/words
        grep '\c.*h\>' /usr/share/dict/words
        grep -F '*' /etc/profile
        touch "*"
        ls "*"
        ls -ld [a-cx-z]*
        "alnum", "alpha", "ascii", "blank", "cntrl", "digit", "graph", "lower", "print", "punct", "space", "upper", "word" or "xdigit".
        ls -ld [[:digit:]]*
        ls -ld [[:upper:]]*

***************************************************************************
Common Shell Features:
        Command Meaning
        >                Redirect output
        >>                Append to file
        <                Redirect input
        <<                "Here" document (redirect input)
        |                Pipe output
        &                Run process in background.
        ;                Separate commands on same line
        *                Match any character(s) in filename
        ?                Match single character in filename
        [ ]                Match any characters enclosed
        ( )                Execute in subshell
        ` `                Substitute output of enclosed command
        " "                Partial quote (allows variable and command expansion)
        ' '                Full quote (no expansion)
        \                Quote following character
        $var        Use value for variable
        $$                Process id
        $0                Command name
        $n                nth argument (n from 0 to 9)
        $*                All arguments as a simple word
        #                Begin comment
        bg                Background execution
        break        Break from loop statements
        cd                Change directories
        continueResume a program loop
        echo        Display output
        eval        Evaluate arguments
        exec        Execute a new shell
        fg                Foreground execution
        jobs        Show active jobs
        kill        Terminate running jobs
        newgrp        Change to a new group
        shift        Shift positional parameters
        stop        Suspend a background job
        suspend Suspend a foreground job
        time        Time a command
        umask        Set or list file permissions
        unset        Erase variable or function definitions
        wait        Wait for a background job to finish
************************************************************************

/etc/profile,/etc/bashrc,/home/zhangleivod/.bashrc,/home/zhangleivod/.bashrc_profile
以上配置文件的执行顺序如下:
1.hello,this message is from the bottom of file /etc/profile
2.hello,this message is from the file of /etc/bashrc
3.this message is from the file of /home/zhangleivod/.bashrc
4.hello, this messgae is from the file  /home/zhangleivod/.bashrc_profile

执行bash命令:
hello,this message is from the file of /etc/bashrc
this message is from the file of /home/zhanglei/.bashrc

/etc/profile,/etc/bashrc中的环境变量属于所有shell

getopts 打开bashell的帮助文档,包含内部命令帮助
zmore

touch file{1,2,3,4}.xml
tee file{1,2,3,4}.xml
***************************************************************************
for:
        The return status is the exit status of the last command that executes. If no commands are executed because
LIST does not expand to any items, the return status is zero.
for NAME [in LIST]; do COMMANDS; done
        example:
        #!/bin/bash

        for i
                do ls -l $i
        done
        # bash testfor.sh /etc/ /home

while:
        while CONTROL-COMMAND; do CONSEQUENT-COMMANDS; done
The return status is the exit status of the last CONSEQUENT?COMMANDS command, or zero if none was
executed.
        example:
        #!/bin/bash
        # This script opens 4 terminal Window
        i="0"
        while [ $i -lt 4 ]
                do
                        xterm &
                        i = $ [ $i + 1 ]
                done

Case:
example:
        #!/bin/bash
        while true; do
                case $choice in
                        1)
                        echo 1
                        ;;
                        2)
                        echo 2
                        ;;
                        3)
                        echo 3
                        ;;
                esac
        done
Select:
        select WORD [in LIST]; do RESPECTIVE-COMMANDS; done
        If in LIST is not present, the positional parameters are printed, as if in $@ would have been
specified.
        The read line is saved in the REPLY variable.
        example1:
                #!/bin/bash
                        echo "this scrpt can make any of the files in this directory private."
                        echo "Enter the number of the file you want to protect:"

                        LIST=`cat list`
                select FILENAME in $LIST;
                do
                        echo "you picked $FILENAME ($REPLY), it is now only accessible to you"
                        chmod go-rwx "$FILENAME"
                done
        example2:
        #!/bin/bash
                        echo "this scrpt can make any of the files in this directory private."
                        echo "Enter the number of the file you want to protect:"
                select FILENAME in *;
                do
                        echo "you picked $FILENAME ($REPLY), it is now only accessible to you"
                        chmod go-rwx "$FILENAME"
                done
        example3:
                #!/bin/bash
                echo "this scrpt can make any of the files in this directory private."
                echo "Enter the number of the file you want to protect:"

                PS3="Your choice: "
                QUIT="QUIT this program -- i feel safe now."

                touch "$QUIT"

                select FILENAME in *;
                        do
                                case $FILENAME in
                                        "$QUIT")
                                                echo "Exiting."
                                                break
                                                ;;
                                        *)
                                                echo "You picked $FILENAME($REPLY)"
                                                chmod go-rwx "$FILENAME"
                                                ;;
                                esac
                        done

                rm "$QUIT"

**************************************************************************
set autoindent
set ts=4

exec vs. xargs
The above find command can be replaced with the following:
        find options | xargs [commands_to_execute_on_found_files]
The xargs command builds and executes command lines from standard input. This has the advantage
that the command line is filled until the system limit is reached. Only then will the command to execute
be called, in the above example this would be rm. If there are more arguments, a new command line will
be used, until that one is full or until there are no more arguments. The same thing using find -exec
calls on the command to execute on the found files every ti me a file is found. Thus, using xargs greatly
speeds up your scripts and the performance of your machine.
**************************************************************************
shift:
        example:
        if [ $# -lt 1 ]; then
                echo "Usage: $0 package(s)"
                exit 1
        fi
        while (($#)); do
        yum install $1 << CONFIRM
        y
        CONFIRM
        shift
        done
This example is very good
***************************************************************************
let和(())都只能对整数进行运算赋值
使用(())时,运算符两边需要有空格
(())算数表达式的值在if和while判断时不用在前面加“$”
[]和test,两者是一样的,在命令行里test expr1和[ expr1 ]的效果相同。他们的三个基本作用是判断文件、判断字符串、判断整数。test和[]中的逻辑运算与或非只能使用-a、-o、!
[[ ]]是内置在shell中的一个命令
        1.支持字符串的模式匹配(使用=~操作符时甚至支持shell的正则表达 式)。逻辑组合可以不使用test的-a,-o而使用&&,||这样更亲切的形式(针对c、Java程序员)。
        2.字符串比较时可以把右边的作为一个模式(这是右边的字符串不加双引号的情况下。如果右边的字符串加了双引号,则认为是一个文本字符串。),而不仅仅是一个字符串,比如[[hello == hell? ]],结果为真。
        3.[[ ]]进行算术扩展,而[ ]不做
        4.[[]]能用正则,而[]不行
        5.[[用"&&"而不是"-a"表示逻辑"与",用"||"而不是"-o"表示逻辑"或"
        6.[[]] 运算符只是[]运算符的扩充。能够支持<,>符号运算不需要转义符,它还是以字符串比较大小
*****************************************************************************








       


       


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.iyunv.com/thread-301182-1-1.html 上篇帖子: shell脚本之安装ansible(centos7环境) 下篇帖子: shell脚本的测试与判断的基础实施
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表