美文网首页数据攻城狮Shell
常用的shell脚本记录

常用的shell脚本记录

作者: classtag | 来源:发表于2016-01-14 00:13 被阅读93次

    主要记录《Linux Shell 脚本攻略》一书很使用的脚本命令,以备用!


    基础入门命令

    1、获取字符串长度

    length = ${#var}
    

    2、获得当前使用的SHELL版本

    echo $SHELL 或 echo $0
    

    3、使用函数添加系统变量

    prepend(){ [ -d “$2”] && eval $1=\”$2\$\{$1:+’:’\$$1\}\” && export $1 ;}
    

    使用方法:

    prepend PATH /opt/myapp/bin
    prepend PATH LD_LIBRARY_PATH /opt/myapp/bin
    

    4、别名的使用

    alias rm=‘cp $@ ~/backup && rm $@'
    

    5、repeat 函数,运行命令直至执行成功

    repeat(){ while :; do $@ && return; sleep 30; done }
    

    命令之乐

    文件查找与文件列表

    1、根据文件名或者正则表达式进行搜索:

    find ~/ -name “*.txt” -print
    find . \( -iname “example*” -o -name “*.pdf” \) -print
    find . -iregex “.*\(\.py\|\.sh\)$”
    

    2、否定参数

    find . ! -name “*.txt” -print
    

    3、基于目录深度的搜索

    find . -maxdepth 1 -name “f*” -print
    

    4、根据文件类型搜索

    find . -type d -print
    #文件类型: 普通文件-f、符号链接-l、目录-d、字符设备-c
    

    5、根据文件时间进行搜索

    #-atime  访问时间
    #-mtime 修改时间
    #-ctime  变化时间
    
    #打印出在最近7天被访问过的所有文件
    find . -type f -atime -7 -print
    
    #-amin 访问时长
    #-mmin 修改时长
    #-cmin 变化时长
    

    6、基于文件大小搜索(k\M\G)

    find . -type f -size +2k
    find . -type f -size -2k
    find . -type f -size 2k
    

    7、删除匹配的文件

    find . -type f -name “*.swap” -delete
    

    玩转xargs

    1、基础

    cat example.txt | xarges -n 3
    

    2、结合find使用xargs

    find . -type f -name “*.txt” -print0 | xarges -0 rm -f
    

    3、统计源码目录中所有java程序文件的行数

    find source_code_dir_path -type f -name “*.java” -print0 | xargs -0 wc -l
    

    相关文章

      网友评论

        本文标题:常用的shell脚本记录

        本文链接:https://www.haomeiwen.com/subject/qrnckttx.html