常用shell命令

shell 调试

代码如下:

    sh -x somefile.sh

在somefile.sh 文件里加上set+x set-x

用 && || 简化if else

代码如下:

    gzip -t a.tar.gz
    if [[ 0 == $? ]]; then
        echo "good zip"
    else
        echo "bad zip"
    fi

可以简化为:

  gzip  -t a.tar.gz && echo "good zip" || echo "bad zip"

判断文件非空

代码如下:

    if [[ -s $file ]]; then
        echo "not empty"
    fi

类似的判断文件是否是软连接:

    if [[ -h $file ]]; then
        echo "system link"
    fi

表达式文档:Shell 基本运算符shell 文件表达式 参数

获取文件大小

代码如下:

    stat -c %s $file
    stat --printf='%s
' $file
    wc -c $file

获取命令行最后一个参数

代码如下:

  echo ${!#} 
  echo ${$#} #错误的尝试

rsync备份

代码如下:

rsync -r -t -v /source_folder /destination_folder
rsync -r -t -v /source_folder [user@host:/destination_folder

批量重命名文件

为所有txt文件加上.bak 后缀:
代码如下:

rename '.txt' '.txt.bak' *.txt

去掉所有的bak后缀:
代码如下:

rename '*.bak' '' *.bak

把所有的空格改成下划线:
代码如下:

find path -type f -exec rename 's/ /_/g' {} ;

把文件名都改成大写:
代码如下:

find path -type f -exec rename 'y/a-z/A-Z/' {} ;

for/while 循环

代码如下:

    for ((i=0; i < 10; i++)); do echo $i; done 
    for line in $(cat a.txt); do echo $line; done 
    for f in *.txt; do echo $f; done 
    while read line ; do echo $line; done < a.txt 
    cat a.txt | while read line; do echo $line; done

删除空行

代码如下:

    cat a.txt | sed -e '/^$/d'
    (echo "abc"; echo ""; echo "ddd";) | awk '{if (0 != NF) print $0;}'

比较文件的修改时间

代码如下:

    [[ file1.txt -nt file2.txt ]] && echo true || echo false
    [[ file1.txt -ot file2.txt ]] && echo true || echo false

实现Dictionary结构

代码如下:

    hput() { 
            eval "hkey_$1"="$2" 
    }
    hget() { 
            eval echo '${'"hkey_$1"'}' 
            }
    $ hput k1 aaa
    $ hget k1
    aaa

去掉第二列

代码如下:

    $ echo 'a b c d e f' | cut -d ' ' -f1,3-
    $ a c d e f

把stderr输出保存到变量

代码如下:

    $ a=$( (echo 'out'; echo 'error' 1>&2) 2>&1 1>/dev/null) 
    $ echo $a
    error

删除前3行

代码如下:

    $cat a.txt | sed 1,3d

读取多个域到变量

代码如下:

    read a b c <<< "xxx yyy zzz"

遍历数组

代码如下:

    array=( one two three ) 
    for i in ${array[@]} 
    do 
      echo $i 
    done

共有三种方式:shell 数组遍历的3种方法

查看目录大小

代码如下:

    $ du –sh ~/apps

查看CPU信息

代码如下:

    $ cat /proc/cpuinfo

date

代码如下:

    $ date +%Y-%m-%d
    2012-12-24
    $ date +%Y-%m-%d –date ‘-1 day'
    2012-12-23
    $ date +%Y-m-%d –date ‘Dec 25'
    2011-12-25
    $ date +%Y-m-%d –date ‘Dec 25 – 10 days'
    2011-12-15

获取路径名和文件名

代码如下:

    $ dirname ‘/home/lalor/a.txt'
    /home/lalor
    $ basename ‘/home/lalor/a.txt'
    a.txt

并集和交集

comm 可以用来求并集,交集,差集,假设现在有两个文件a和b,它们的内容如下:
代码如下:

    $cat a
    1
    3
    5
    $cat b
    3
    4
    5
    6
    7

    $comm a b 
    1
    3
    4
    5
    6
    7

    $comm -1 -2 a b #交集
    3
    5

    $comm a b | sed 's/	//g' #并集
    1
    2
    3
    4
    5
    6
    7

    $comm -1 -3 a b | sed 's/	//g' #b-a
    4
    6
    7

awk复杂分隔符

多字符作分隔符
代码如下:

    $ echo "a||b||c||d" | awk -F '[|][|]' '{print $3}'
      c

多种分隔符1
代码如下:

    $echo "a||b,#c d" | awk -F '[| ,#]+' '{print $4}'
      d

多种分隔符2
代码如下:

    $echo "a||b##c|#d" | awk -F '([|][|])|([#][#])' '{print $NF}'
      c|#d

产生一个随机数

代码如下:

    echo $RANDOM

按照模式split 文件

代码如下:

csplit server.log /PATTERN/ -n 2 -s {*} -f server_result -b "%02d.log" -z
/PATTERN/ 用来匹配某一行,分割过程由此开始
{*} 根据匹配,重复执行分割
-s 静默模式
-n 分割后文件名后缀中,数字的个数
-f 分割后的文件名前缀
-b 指定后缀格式

获取文件名或者扩展名

代码如下:

    var=hack.fun.book.txt
    echo ${var%.*}
    hack.fun.book
    echo ${var%%.*}
    hack
    echo ${var#.*}
    fun.book.txt
    echo ${var##.*}
    txt

以 root 帐户执行上一条命令。

代码如下:

    sudo !!

其中: * !! 是指上一条命令 * !$ 上一条命令的最后一个参数 * !* 上一条命令的所有参数 * !:3 上一条命令的第3个参数
代码如下:

    $ls /tmp/somedir
     ls: cannot access /tmp/somedir: No such file or directory
    $mkdir !$
     madir /tmp/somedir

利用 python 搭建一个简单的 Web 服务器,可通过 http://:8000$HOSTNAME 访问。

代码如下:

    python -m SimpleHTTPServer

在 Vim 中无需权限保存编辑的文件。

代码如下:

    :w !sudo tee %

将上一条命令中的 foo 替换为 bar,并执行。

代码如下:

    ^foo^bar

快速备份或复制文件。

代码如下:

cp filename{,.bak}

将 ssh keys 复制到 user@host 以启用无密码 SSH 登录。

代码如下:

  ssh-keygen
  $ssh-copy-id user@host

把 linux 桌面录制为视频。

代码如下:

    ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg

man 妙用

代码如下:

    man ascii
    man test

在 vim 中编辑上一条命令

代码如下:

    fc

删除0 字节文件或垃圾文件

代码如下:

    find . -type f -size 0 -delete
    find . -type f -exec rm -rf {} ;
    find . -type f -name "a.out" -exec rm -rf {} ;
    find . type f -name "a.out" -delete
    find . type f -name "*.txt" -print0 | xargs -0 rm -f

在编写SHELL 时显示多行信息

代码如下:

    cat << EOF
    +--------------------------------------------------------------+
    | === Welcome to Tunoff services === |
    +--------------------------------------------------------------+
    EOF

注意,在指定结束符时,它必须是该行的唯一内容,并且该行必须以这个字符开头。

如何给mysql建软链接

代码如下:

    cd /usr/local/mysql/bin
    for i in *
    do ln /usr/local/mysql/bin/$i /usr/bin/$i
    done

获取IP地址:

代码如下:

    ifconfig eth0 |grep "inet addr:" |awk '{print $2}'|cut -c 6-

打开文件数目

代码如下:

    lsof

清除僵尸进程

代码如下:

    ps -eal | awk '{ if ($2 == "Z"){ print $4} }' | kill -9

打印唯一行

代码如下:

    awk '!a[$0]++' file

打印奇数行

代码如下:

    awk 'i=!i' file
    awk 'NR%2' file

打印匹配行后的某一行

代码如下:

    seq 10 | awk '/4/{f=4};--f==0{print;exit}'

打印某行后后面的10行

代码如下:

    cat file | grep -A100 string
    cat file | grep -B100 string #前面
    cat file | grep -C100 string #前后
    sed -n '/string/,+100p'

    awk '/string/{f=100}--f>=0'

输出重定向

如果你愿意,可以将STDERR 和 STDOUT 的输出重定向到一个输出文件,为此,bash 提供了特殊的重定向符号 &>;若是不明白,可以参考:linux下详解shell中>/dev/null 2>&1
代码如下:

    ls file nofile &> /dev/null

我们如何在脚本里面重定向呢?没有什么特别之处,和普通重定向一样。
代码如下:

    #!/bin/bash
    #redirecting output to different locations
    echo "now redirecting all output to another location" &>/dev/null

如果我们要将所有的输出都重定向到某个文件,可以用exec 来永久重定向,如下所示:
代码如下:

#!/bin/bash
    #redirecting output to different locations
    exec 2>testerror
    echo "This is the start of the script"
    echo "now redirecting all output to another location"
    exec 1>testout
    echo "This output should go to testout file"
    echo "but this should go the the testerror file" >& 2

输出结果如下所示:
代码如下:

    This is the start of the script
    now redirecting all output to another location
    lalor@lalor:~/temp$ cat testout 
    This output should go to testout file
    lalor@lalor:~/temp$ cat testerror 
    but this should go the the testerror file
    lalor@lalor:~/temp$

以追加的方式重定向:
代码如下:

    exec 3 >> testout

取消重定向:
代码如下:

    exec 3> -

函数

任何地方定义的变量都是全局变量,如果要定义局部变量,需加local 关键字
shell中的函数也可以用递归
代码如下:

    #!/bin/bash
      function factorial {
          if [[ $1 -eq 1 ]]; then
              echo 1
          else
              local temp=$[ $1 - 1 ]
              local result=`factorial $temp`
              echo $[ $result * $1 ]
          fi
      }

      result=`factorial 5`
      echo $result

创建函数库
将函数定一个在另一个文件,然后通过source 命令加载到当前文件
在命令行使用函数
将函数定义在~/.bashrc 中即可
向函数传递数组
代码如下:

#!/bin/bash
    #adding values in an array
    function addarray {
        local sum=0
        local newarray
        newarray=(`echo "$@"`)
        for value in ${newarray[*]}
        do
            sum=$[ $sum+$value ]
        done
        echo $sum
    }

    myarray=(1 2 3 4 5)
    echo "The original array is: ${myarray[*]}"
    arg1=`echo ${myarray[*]}`
    result=`addarray $arg1`
    echo "The result is $result"

字符串替换

代码如下:

    ${string//pattern/replacement}
    a='a,b,c'
    echo ${a//,/ /}
    5. Contains 子字符串?
    string="My string"
    if [[ $string == *My* ]]; then
        echo "It's there!"
    fi

创建目录

递归创建目录,即使上级目录不存在,会按目录层级自动创建目录,代码如下

    mkdir -p ${ToolsPath}
原文地址:https://www.cnblogs.com/meiguhuaxian/p/12960517.html