前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >【笔记归档】shell学习笔记

【笔记归档】shell学习笔记

原创
作者头像
fankhu
修改2023-06-20 14:04:55
1.3K0
修改2023-06-20 14:04:55
举报

1. bash 调用环境

        1.1=> 登录/非登录shell
                $0 => - 
                -        l, --login

1.2=> 交互/非交互shell

                标准输入和标准错误都连接到终端(tty), 不使用-c选项(及不含非选项参数)
                交互式shell的特点:[[ -n $PS1 ]] && [[ $- ~= “i” ]
                loginshell的特点:echo $0 时,显示-bash
    -i       
    设置PS1, $-包含i选项 (可以从shell脚本中测试这)

1.3 登录shell or --login (交互式,非交互) /etc/profile, ~/.bash_profile, ~/bash_login, ~/.profile (~/.bash_logout, 退出时)

--noprofile  可以阻止上述行为

交互shell非登录shell ~/.bashrc

--norc

--rcfile

1.4 非交互shell, 或者是后台脚本, ~/.bashrc --rcfile --norc

$BASH_ENV 展开,  并在但前shell下执行它(source)

1.5 bash, sh的区别 posix

     补充:chsh -l        #列出系统上可用的shell
              chse -s         #设置修改自己的shell

2. 基本定义

blank

word

name

2.1 元字符, "未被引用的"

 | & ; ( ) < > \ space tab

2.2 控制操作符

||
&& &
;
;; 
( )
| 
 <newline>

3 shell 保留字

    ! case do done elif  else esac fi for function if in select then until while { } [[ ]]

4. Shell 语法

4.1 简单命令 space <newline>

4.2 管道 一个或者多个由 | 连接的命令序列,格式如下:

command1 | command2

其中,command1的 标准输出被连接到command2的标准输入

4.3 list 组合命令:

       ( list )   list 在子进程中执行

       { list; }  list 在当前进程中
------

       (( expression )) 算数扩展

       [[ expression ]]      #注意要有空格 [[ 2 -lt 5 ]]&&echo yes||echo no
                                                         # !!!  [[ ]]中可以使用 test命令的大部分参数        
                                                         # [[ $a = "hi" ]]  此时一个等号 = 也表示相等,但必须有空格
                          gt ge lt le eq ne   
                          == != =~
                          -z             # 字符串为null
                          -n                         # 字符串不为null
                          -a                         # 逻辑与
                          -o                         # 逻辑或
                          -e FILE        # File exists
                          -d FILe                  # File exists and is a directory
                          -x FILE             # File exists and execute
                          -f FILE                 # File exists and is a regular file
                          -s FILE                 # File exists and has a size greater than zero
                          -r FILE        # File exitts and read permission is granted
                             # 更多参数请参考 test命令                           
                          ! expr1 
                          expr && expr   # if [[ $# -eq 1 && $1 == "all" ]]; then
                          expr || expr   

[[ ]]内不进行: 路径名扩展,单词分割 进行: 参数扩展 变量扩展 算数扩展 波浪号扩展 命令置换 $(cmd) `cmd` 进程置换

4.4 循环控制语句

      for name [ in words ]; do list; done
       for ((i=0; i<=5; i++)); do list; done

        select name [ in words ]; do list; done

        case word [ in [(] pattern1|pattern2 ... ) list ;;]; ... esac
                case $action in
                  push) test "push1";test 'push2';;
                  *)usage;;
                        esac

        if list; then list; [ elif list; then list; ] ... [ else list; ] fi
                                     #if [[ $1 -ne 3 ]];then ... fi
                                                         # 空语句可用一个冒号“:”来表示执行任何动作。

        while list; do list; done 
                                     # while [ 0 ];等价于 while : ;
                        
        until list; do list; done
                ## while 常用例子
                getopts 常在循环中运行,用于参数检查,冒号:表示选项后带有参数,该参数会保存在OPTARG变量中
                    getopts options variable
                        # while getopts h:ms opt;do
                           case $opt in
                           h)  ;;
                           m)  ;;
                           s)  ;;
                           \?) ;;
                          esac
                          done
            while read line
                do
                   echo $line
                done < FILE
                ##每次循环读文件的一行数据
                
                ##批量传文件,在iplist中ip root密码相同时适用 
                while read ip;do rsync -avz ./installpackage.sh root@$ip:`pwd`;done < ./iplist

4.5自定义函数

                function keyword () {}
                keyword () {}

                [ function ] name () [{组合命令}]

5 引用

    从特定字符或者单词中移除特殊意义
    保护一些保留字不被解释

    \       # 转义符
        \b           # 退格键
    \t      # tab
    \v
    \
    \\ 
    \nnn    # 8 进制   \0nnn  以数字0开头

    \xHH    # 16 进制

    \c      # 控制字符,比如\cx

    ''      # 保护字面值

    ""  $,` # 保留特殊意义, 
                
                    # \: $, `, \, ", <newline> 保留字符

6 参数

参数是存储一个值的入口

可以是一个名称,数字, 也可以特殊字符

6.1 变量, 被标记了名称的参数

                赋值
                name=[value]
                alias export declare readonly local    
                
                array=(wordlist)
                array[index]=value
                注:数组声明的5种方法
                    1) array[key]=value   #array[1]=a,array[2]=b
                        2) declare -a array
                        3) array=( v1 v2 v3 ...) 
                        4) array=( [1]=a [2]=b [3]=c ... )
                        5) array="a b c"      # echo ${arr[0|@|*]}  把array变量当做数组处理,但数组元素只有字符串本身
                
                    遍历数组每个元素:for i in ${array[@]};do echo $i;done
                        
                #   获取数组最后一个元素:
                       arr=( aa bb cc )
                           echo ${arr[@]: -1}
                #   数组元素切片:
                     ${TMP_ARR[@]:1:2}
                         ${TMP_ARR[@]:1:$((${#TMP_ARR[@]}-2))}  #取第2至倒数第2个元素
                  
                【取消变量: unset 】        

6.2 位置参数

                1 - N, 除 0 之外     # $1 ... $N

6.3. 特殊变量

       *
       @  所有位参
                                        #没有双引号时,$*, $@ 是相同的
                                        #有双引号时: "$*" 把所有位参扩展为一个单独的字符串,这个字符串用空格(默认)把所有位参连接起来。
                                        #    类似这样: "$1c$2c$3c$4" c 是连接字符(默认空格)
                                        #            "$@" 则把每个参数扩展成独立的单词, 类似这样: "$1" "$2" "$3"
       #    # 参数长度 ,位参个数
       ?    # 上一条命令的返回值
       $    # pid 
       -    # 减号 shell信息
       !    # 最近一个在后台执行的pid
       0    # 脚本名/shell名称
       _    # 下划线,上一条命令最右边的参数
           
           补充:写后台脚本好习惯,第一行必增加  source /etc/profile 初始化环境变量

6.4 shell内建变量

       PS1          # shell提示符
       PATH         # 给PATH添加其他目录 在~/.bashrc 中加入 export PATH=$PATH:/目标目录 注销后登陆即可
       RANDOM
       PWD       
       OLDPWD  
       PPID         # 父进程ID
       BASH_VERSION
       LINENO

7. 扩展

7.1 花括号扩展

         生成字符串     #{a..z}  {1..6}   试试 echo {a..c}{1..3}的输出结果

7.2 波浪号扩展

         ~   HOME
         ~+  PWD
         ~-  OLDPWD

7.3 参数扩展

        ${param}     
    ---------------
        ${param:-value}     #使用默认值  param
        ${param:=value}         #赋默认值
        ${param:?value}         #显示错误
        ${param:+value}         #使用其他值
        ${param:offset}
        ${param:offset:length}
    ----------------
            var=${param=value}  #当param非空,var为param值,当param为空,将var设为空
                var=${param-value}  #当param非空,var为param值,当param为空,将var设为value,param还为空
        ${!prefix*}                 #匹配名称前缀
        ${!prefix@}                        #等价于 ${!prefix*}

        ${!name[@]}         #列出索引值

        ${#param}                      #参数长度,param也可以为一个数组
        ${#param[@]}                   #元素个数
        ${#param[*]}

        ${param#word}                               #移除匹配前后缀,${param#*/} 移除第一个/及其左边的字符串
        ${param##word}                               #${param##*/} 移除最后一个/及其左边的字符串
        ${param%word}                                #${param%/*} 移除最后一个/及其右边的字符串
        ${param%%word}                                #${param%%/*} 移除第一个/及其右边的字符串

        ${param/pattern/string}               #用string替换第一个pattern    echo ${array[@] /#o/k}  符号#在pattern中同样适用
        ${param//pattern/string}              #用sing替换所有pattern
                ${param}string                 #追加string到$param后赋值,param本身内容不变,but,pp=${pp}abc:

7.4 命令置换

        使用命令输出来替换命令名称
        $(cmd)
        `cmd`                          # a=$(cmd)

7.5 算数扩展

        $(( expression ))              # a=$((3+3))
        (( ecpression))                # ((b=3+3))
                                               #(( exp1,exp2..expn))的执行结果是括号内最后一个expn的结果,
                                                                           #(( exp ))内表达式执行正确后,返回值为0 (返回值不同于执行结果)
        $[ expression ] (bash-4.0)     # a=$[3+3]  a=$[3**3]

7.6 进程置换 !!

        在支持命名管道或者使用/dev/fd命名打开的文件的系统中

        >(list)  => /dev/fd/60
        <(list)  => /dev/fd/61

        list 的标准输入或输出连接到FIFO管道或者是一个打开的文件描述符/dev/fd

        : 当作参数传递给命令
                -------
                >(cmd)    #命令cmd运行时,它的标准输入会链接到到FIFO或者/dev/fd/中的文件,对这个文件的写入操作会被当作命令cmd的标准输入
         测试:
           echo "aaa bbb cccc" > >(awk '{print $2}')   输出bbb

                <(cmd)    #当这个形式作为命令的参数传递时,在/dev/fd/中对应的文件将被读取获得cmd的标准输出
        测试:
            awk '{print $2}' <(echo aaa bbb ccc)    输出bbb
            read v1 v2 v3 < <(echo aaa bbb ccc)     此处第一个<表示标准输入,第二个<表示进程置换,
               echo $v1 $V2 $v3    分别得到aaa bbb ccc

7.7 单词分割

        shell 扫描命令行经过参数扩展,命令置换以及算数扩展后没有在双引号中间的结果进行单词分割
        它吧IFS变量中的每一个字符当作是定界符,然后把其他扩展的结果按这些定界符分割开
        如果IFS没有设置,或者它的值正好等于 一个空格接一个跳格接一个换行符, 默认情况下,在扩展结果
        中位于最前端和最末端端的空格,跳格,换行将被忽略, 其他位置的空格,跳格,换行当作分割字。

        如果设置了与默认值不一样的IFS,那么首尾的空格,跳格都被忽略。
        只要在IFS中包含有空白字符(空格,跳格), IFS中任何非IFS字符与IFS空白字符共同定界一个域。IFS
        空白字符序列也被当成delimiter, 如果IFS是null值,则不会进行单词分割

7.8 路径名扩展

        对命令行的所有字符进行扫描,检查* ? [...] 等符号,当作pattern进行文件名称匹配,按照字母顺序排序
        *      匹配任意字符包括null串
        ?      匹配单个字符
        [...]          匹配其中的任意字符, 如果[之后接的是!,或者^则表示其中的都不匹配。
               ] 怎么处理?

                注意:shopt, set   # shopt,toggle the values of variables controlling optional shell behavior.
                  shopt:
                        -s enable(set)  # 在bash中输入不带参数的 shopt命令,会显示shell的属性列表,可根据列表中的项目进行-s 或 -u
                        -u disable(unset)

                        nullglob, 
                        extglob

8, 重定向

8.1 使用特殊符号,重新定义输入的来源和输出的去向。

8.2 用于打开或者关闭文件描述符


                发生时间: 在命令执行前进行
           example:        echo >std_out 2>&1
                                ls bbbb ? 2>&1 >std_out
              Q:   为什么标准错误没保存 ?

8.3 三个基本的文件描述符: 0, 1, 2

        0: 标准输入
        1: 标准输出
        2: 标准错误     #  find -name /bash.rc >list_right 2> /dev/null 将标准错误重定向到垃圾桶

        [n]<file                   #文件file被打开, 在文件描述符 n 上进行读操作(默认0)
        [n]>file                   #文件file被打开,在文件描述符 n 上进行写操作(默认1)
                        #自动创建
                 选项 set -C => !write

        追加重定向输出
          [n]>>file

        同时重定向标准错误和标准输出到相同的文件(描述符)
            &>file, >&file
            或者: >word 2>&1
                        
                        
                # 将变量内容作为程序输入

        EXP='1+1'

        bc -q <<< "${EXP}"                

8.4 here document: #将doc content作为标准输入,

        <<[-]FLAG
            doc content
        FLAG

        -表示: 忽略doc content部分的前导的tab
        FLAG加上单引号时,doc content内容不进行变量扩展,进程置换,命令置换,
                example: cat << FLG
                         >$PATH
                                 >`date`
                                 >FLG
                                 结果会对输入的内容进行扩展
                补充:shell script 多行注释(在vi环境下)
                      :<<FLAG
                            content
                          FLAG

8.5 here string:

 # A variant of here documents,the 'string' is expanded and supplied
 # to the command on its standard input.
# 将string分割为一个个单词
   <<<string
   # cat <<<`date`

8.6 移动文件描述符 # 符号‘-’表示关闭m,如果不加'-',复制m到n,不关闭m

        [n]<&m-                 #文件描述符m被复制到n(或者标准输入)后,关闭m
        [n]>&m-                 #文件描述符m被复制到n(或者标准输出)后,关闭m

        n<>file                 #打开文件file,使用描述符n同时进行读写操作
                
 example:

 移动文件描述符:
     exec 5<&1-  #复制读文件描述符1到5(fd5),然后关闭1(fd1),  执行此步骤后 echo abc 会提示bad file descriptor,
                 #因为默认echo到fd1, 但是echo abc >&5 可以在屏幕上显>示,因为5是复制的fd1(链接到终端),而且fd5没有被关闭
            
     exec 1<&5-  #恢复文件描述符1, 然后关闭fd5, 这个时候,echo abc就正常了,

8.7 关闭文件描述符:

                        exec n>&-   #关闭描述符n的写操作
                        exec n<&-   #关闭描述符n的读操作

9 shell 内建函数 #man builtins中有更详细的介绍

                getopts         #getopts is used by shell procedures to parse positional parameters.
                                #可在shell脚本中 增加选项和参数,如 getopts h:ip name
                trap                     #trap [-lp] [[arg] sigspec...] 
                                                #The commad 'arg' is to be read and executed when the shell receives signal 'sigspec'.
                                                #例如:$ trap "echo "test trap"" INT   在当前shell下 按 Ctrl + C  显示 test  trap
                                                #      $ trap "echo 'exit time : '`date`>>exit.date" EXIT
                                                # trap -p  prints the list of commands asscociated with each sinal.
                                                # trap -l  print a list of signal names and their corresponding numbers.  
                source          #在当前shell下执行shell script
                alias                        #别名
                break
                declare                        #声明变量
                                 num=10
                                                 declare id$num=hello    #变量名拼接
                eval                         #将变量内容当做命令执行 a=ls;eval $a
                                #一个示例:aa="a=10;echo '$a'"  注:此处$a应加单引号,否则会变量置换
                                                #          eval $aa     (等价于echo `eval $aa`)
                exec            # exec [-cl][-a name] [command[arguments]]
                                #If command is specified ,it replace the shell.No new process is created.
                                                #The argument become the arguments to command.执行exec后,不返回当前的执行过程。
                                                #注:exec 在对文件描述符进行操作的时候,也只有在这时,exec 不会覆盖当前的 shell 环境。
                export                        #把本地变量变为环境变量  用户退出系统后依然有效
                fg                            #把后台任务放到前台, 注: ctrl + z  把当前任务放到后台
                let             #数学运算,可移植,比(( exp)) 通用
                                #let a=9*6
                                                #let a=3 b=4**2
                                                #let "t1 = ((a = 5 + 3, b = 7 - 1, c = 15 - 4))"  
                                                #echo "t1 = $t1, a = $a, b = $b"        
                wait                        #等待后台进程完成
                                # sleep 20&
                                                # wait

10 常用shell工具

man  [command]
ls              #  ls -l -a -t(按修改时间排列) -u(按最新访问时间排列)
                                                          -R 显示子目录内容
                                                #  ls -lh   h 表示human-readable
                                                #  ls --block-size=KB -l
                                                #  ll --time-style=long-iso   显示完整的时间格式  详情查--time后可跟的参数
                                                #  ls -d */
head                        #  head 从文件头读取,
tail                        #  tail从文件尾读,
 sed,            #  替换、删除  【查看info sed】
sed 's/REGEXP/REPLACEMENT/FLAGS'
      #        `s/REGEXP/REPLACEMENT/FLAGS'.  The `/' characters may be uniformly
      replaced by any other single character within any given `s' command.
      The `/' character (or whatever other character is used in its stead)
      can appear in the REGEXP or REPLACEMENT only if it is preceded by a `\'  character.
      sed -i /ddd/d test  删除匹配行
      sed -i 13,15d test  删除13到15行
      sed -i '/^46/s/|$//' 65535_201504*.log  #替换指定行的末尾字符
      sql=$(echo $sql|sed "s/'/\\\'/g") # 将单引号替换为\'
                                                                
      # 整行替换
                sed '11c abc' t.log  把11行替换为abc
      # 删除匹配行及后两行 sed '/xxxx/,+2d' file
      # 删除第一个匹配项和第二个匹配项之间的行,
             sed '/regexp1/,/regexp2/d' file
      #Flag:  [g] [NUMBER] [p] [w filename]

grep                       
 #  grep 提取行 
    grep -A num pattern file  #Print NUM lines of trailing context after matching lines
         -B num  #打印匹配的前num行
         -C num  #打印匹配的前后num行
         -num    #打印匹配的前后num行        
          相同行    grep -xFf  filename_a   filename_b
           不同行   
           filename_b特有行 grep -vxFf filename_a filename_b
         grep -E ?tt file.txt            # -E 扩展正则
         grep -E -e ?tt -e *ho file.txt  #匹配多个
         严格匹配
         ps axuw |grep -o -E '\-\-lang=\S+'

find            #  find 在目录中查找文件,可遍历子目录
    find [path] [option] [action]
    find -name sh0*.sh
    find max.a -exec cp {} course/ \; 
    对find找出的文件进行其他命令操作,{}表示找到的内容 【注意最后要以\;结尾】
    find . -name '.#*' -depth -delete
    find /var/tmp/stuff -mtime +90 -print0 | xargs -0 /bin/rm
    find -size [+][n][c] n表示n block长度(1block=512bytes),c表示1 character, +表示大于
    find -name "*.0" -o -name "*.temp"    -o或
    find -atime +5 \( -name "*.o" -o -name "*.tmp" \)  将括号内看成一个unit
    find -type [d][f][s] d:directory  f:plaim file  s:socket
    find . -type f -size +10M  删除大于10M的文件
    find . -user root    #查找属主为root的文件
    find . -empty        #查找目录下空文件
    find . -type f  -print0 | xargs -0 sed -i "s/${remote_ip}/${inip}/g" # 批量替换某路径下文件内容
 seq,                        #  seq 产生序列 
                stat,                         # stat filename  查询文件状态 

 date,          
  # 使用 info date 可以找到很多有用的示例,如date --date='2013-8-9 14:12:12' +%s
    修改系统时间 date -s  
    date -s 19:15:02
    date -s "2013-11-30 12:12:00"
    TIME=$(date +%Y%m%d-%H%M)
 # 输出unix时间
    date +%s
    date -d '2014-0808 22:22' +%s  # 将指定时间转化为unix时间
                                                  
  # 一分钟前
    date -d '1 minutes ago'
                                                  
  # 一分钟后
    date -d '1 minutes'
                                                 
  # 将unix时间转为普通时间
    date -d @1407168459 
    date -d @1407168459 +%Y%m%d
                                                  
#  cat /etc/sysconfig/clock  查看时区配置                  

bc              #计算  echo "3+3"|bc

 locate,         # locate filename  根据文件名查找文件 ,结合updatedb使用

ldd,            # ldd查询动态链接库
ldconfig,       # configure dynamic linker run time bindings
                # ldconfig会读取/etc/ld.so.conf 中的路径,因此在该文件中应该包含/usr/lib等目录

sync            # flush file system buffers
rsync          # 快速便捷的远程文件拷贝工具
               rsync [option...] SRC [DEST]
               rsync -avz [USER@]HOST:SRC [DEST]   #保留原始文件属性,压缩传输
               rsync -q file                       # 测试文件是否存在

scp,            # 远程文件拷贝

ifconfig        # ip信息
                ifconfig eth1 |awk '/inet addr:/ {print substr($2,6)}'
sort            # 排序   sort -u 排序并去重
                
                # cat 1.txt 2.txt | sort -n | uniq -d 取两个文件交集

wc              # 统计文件行、字、字符数         wc -l 显示文件行数
uniq            # 去重 (常与sort结合使用)
cut             # 切片行数据  cut -f1 file 提取文件每行第一个field数据
tr          [-ds] set1        # -d 删除字符set1   
                                -s  set  根据set内容对输入去重。
            tr '[A-Z]' '[a-z]'
expand          # 将tab转为空格

               # expand a.txt|tr -s " "|sed 's/ /|/g'    将tab转为空格,让后将多个空格转为一个空格并替换空格为|                

col [-xb]       # -x 将tab键转为space  -b 文字内有反斜杠时,保留反斜杠最后接的字符
                # col 常用于tab替换,也可用于将man page转换为纯文本!
                # man bash | col -b > bash_manual.txt
join            # 文件内容合并 ,合并前文件应排序 join <(sort file1) <(sort file2)
uname           # 打印系统信息 uname -a 显示所有信息 -r显示内核release版本
                -s 内核名称        -i 硬件型号
                 -n 主机名

cat /proc/cpuinfo   【查看cpu主频等信息】

expr            # expr EXPRESSION
                expr 2 - 1
               expr length "hello"
md5sum          # md5sum filename > filemd5 生成filename的MD5值并将MD5值及文件名写入filemd5
                md5sum -c filemd5  从filemd5中读取MD5值并验证对应的文件

certutil -hashfile yourfilename.ext MD5  windows系统下查看md5  
 shutdown        #关机
                shutdown -r 关闭系统服务后重启
                -h 关闭系统服务后关机
expect          #用程序来处理交互式程序的对话 可在脚本中处理一些需要输入交互参数的命令,如ssh,scp等
                # 关键字:set spawn expect send 
                         spawn 启动一个shell命令
                         set 设定变量
                         expect "关键字"  捕获spawn中命令的返回的结果
                         send "关键字"   向命令发送消息
                         
                -----t.ep----
                #!/usr/bin/expect -f
                set password abcde
                set file [lindex $argv 0]  #增加外部参数
                spawn scp user@xx.xx.xx.xx:/data/home/aa/$file /data/home/user00/
                set timeout 300
                expect {
                        "no)?" {send "yes\r"
                                        set timeout 300       #设定超时时间
                                        expect "assword:"
                                        send "$password\r"        
                                   }
                        "assword:" {send "$password\r"  }
                                }
                 set timeout 300
                 send "exit\r"
                 expect eof
                 

                 
           #用法: ./t.ep test.txt

clear 清屏
reset 终端初始化,(和清屏有点像)

xargs # 通过标准输入建立并执行命令行
      # ls *|xargs touch  将ls的执行结果
      # ls *|xargs -0     将ls的输出作为普通字符 ,即空格、引号等被作为普通字符
      # find /tmp -name core -type f -print | xargs /bin/rm -f
 ulimit   # -a all current limits are reported
          # -c core文件大小限制
          # -n the maximum number of open file

 screen   # screen是一个可以在多个进程之间多路复用一个物理终端的窗口管理器
          # 启动 screen
          # 挂起 Ctrl +a +d
          # 恢复 screen -ls   找到挂起的会话ID  screen -r ID
          # 增加screen窗口 继续在已有screen会话中输入 screen 
          # 命名screen 窗口 Ctrl +a +A
          # 新建一个指定名称的screen 窗口 screen -t name
          # 在不同窗口间切换 ctrl + a + num 
          # 杀掉当前窗口     ctrl +a k
          # 增加屏幕下方screen标签
          #关闭屏幕闪烁:/etc/screenrc设置 vbell off
          # 在用户主目录新建文件 .screenrc 增加
             hardstatus on
             hardstatus alwayslastline
             hardstatus string "%{.bW}%-w%{.rW}%n %t%{-}%+w %=%{..G} %H %{..Y} %m/%d %C%a"
             vbell off

#与路径相关的命令
      readlink -f
      dirname   $_PATH
      basename $_PATH
                 
     eg.
       SELF_PATH=$(readlink -f $0)
       SELF_DIR=$(dirname $SELF_PATH)
       SELF_NAME=$(basename $SELF_PATH)

11 打包及压缩工具

-------------

tar,           # 压缩      tar -jcv [-f 新文件名] filename    -j  bzip2格式
               # 解压缩    tar -jxv [-f 待压缩文件] -C 目标目录
                        # zip格式打包         tar -czvf test.tgz test/    
                                 tar -xvzf test.tgz
                        #        tar -czf test.tgz -T ./t        将./t中的文件打包至test.tgz  
              tar.gz, gz, tgz,                                                

gzip          # gzip file 
              # gzip -c file > file.gz
gunzip        # gunzip   file.gz    解压后file.gz将被删除 
bz2, tar.bz2
             # bunzip2 file 解压
 zip,            # zip -r foo.zip foo  压缩目录时要加-r 参数,否则压缩的只是一个空目录

12 linux UGO权限及文件类型

12.1用户管理

--------

useradd         # root拥有此权限,useradd username
                  useradd -m -d /data/home/game game    -m建立用户主目录 -d HOME_DIR
                  useradd -d /data/qqpet  -g users -G users -m qqpet -u 500  ; echo xxx | passwd --stdin qqpet
passwd          # root建立用户时可给该用户设立初始password,passwd usrname.
                # 用户也可以使用此命令更改password
chpasswd        # 批量修改密码  chapasswd -e file  ,其中file格式为 username:password
                echo "user:userpasswd"|chpasswd
                                                  
usermod                        # 修改使用者账号

chmod           # chmod 764 filename     r:4  w:2  x:1       
chown           # change file owner and group.
                # chown -R owner:group filename  将目录子文件权限也改变,-R recursive
                
who             # show who is logged on
                
w               # show who is logged on,查看机器负载
                # 第一行输出的内容
               09:41:41 up 162 days, 20:44,  2 users,  load average: 0.31, 0.14, 0.10
                # load average后的3个数据依次表示 1分钟负载、 5分钟负载、15分钟负载 ,单位时间段内活动进程数
                # 通常这个值小于cpu个数就认为负载正常 
                
# cat /proc/cpuinfo|grep processor|wc -l  查看CPU信息
                                                
                
uptime                    # Tell how long the system has been running
                
finger          # finger [-sm] username    列出用户信息

su              # switch user       sudo su - username   “ - ”可以载入用户环境变量
sudo            # sudo -u user00 crontab -e  以用户user00执行后面的命令
                # sudo -l 查看当前用户有哪些命令的sudo权限
                
/etc/passwd     # 本文件中列出了所有用户信息
/etc/rc.local   # 系统启动时运行的的指令(用户可自定义) 或是:/etc/rc.d/rc.local
/proc/cpuinfo    # 查看CPU信息  lscpu

12.2文件管理

   --------
rename          #  批量修改文件名, rename from to file

du                                #  du显示文件空间的使用情况         du filename
                                                                                                                        du -sh * 查看当前目录下文件空间 (常用)
df              #  df 显示文件系统磁盘空间的使用    df -B M   以M为block单位显示磁盘空间情况
                                                                    df -h
                                                
touch           #  touch更新文件访问及文件修改时间,
                #  批量建立文件 touch file_{1..10}.log,建立10个文件
mkdir           #  mkdir -p path1/path2/file   如果目录不存在,先建立目录

install         #  install 拷贝同时修改文件属性lockfile                  
 mktemp         #  mktemp建立一个临时文件(具有独特文件名,只对拥有者可读写,更具安全性)     
                            
cp              #  cp 复制文件或目录 cp -r 复制全部的子目录                                 
lockfile                             
                # 文件的三种时间 change time , modify time (对内容进行修改), access time
rm              # rm -r 递归删除文件及子目录 -f 强制删除  rm -rf
                # 为了避免误删,可以按相对路径进行删除,如 cd /data/log/201601/ && rm -rf  *.log
                
rmdir           # 删除空目录

ln              # 创建链接文件,ln -s target linkname  创建软连接(symbolic link),相当于指针,链接直接指向原文件
                  ln target linkname  创建硬链接 ,删除target,链接文件依然存在
                  删除软连接    rm -rf linkname    注意:千万不要写成 rm -rf linkname/ 否则会悲剧的
dd              # 文件备份与恢复命令
                
ipcs            #查看共享内存 ipcs -m
ipcrm           #释放共享内存  ipcrm <shmid>
                
swapoff         #关闭swapfile   
                swapoff /swapfile1
                rm /swapfile1

12.3 通配符

    ?              #匹配一个字符
    *                                #匹配任意字符
     [...]                   #匹配括号内任意一个字符

13 进程与网络

----------


kill,           # 杀死进程  
                kill -9 PID
killall         # killall 进程名                                                   
ps,             # ps显示进程 
                 ps   -ef | -f
                 ps -U game l   显示用户game的所有进程,l表示全名称
                                                  
                 ps -e -o 'pid,comm,args,pcpu,rsz,vsz,stime,user,uid'
                                                  
 top,            # top 显示linux 系统任务信息(动态显示)
                 # 按键 1 显示多个CPU信息
                   M 按照内存使用排序        
                   P 按CPU占用率大小排序
                   q 退出                                                  
                
                
pkill,          # pkill will send the specified signal (by default SIGTERM) 
                # to each process,默认发送kill信号
pgrep           # 根据进程名查找PID
                 pgrep process_name
                 pgrep -u user00 process_name

lsof            # list open files 
                  lsof -a -p <pid> -d 0-2
wait            
sleep
netstat         #打印网络连接、路由表、接口统计、masquerade connections(虚拟链接), multicast memberships
                 netstat -rn 路由
                netstat -ant 端口
uname -a        # 查看内核信息 系统位数
                
tcpdump         # linux 抓包命令
                tcpdump -i tunl0 -nn port 8080 or port 443 or port 8000 
               #  监听指定网卡
                  tcpdump -i eth1
                  sudo tcpdump -i eth0

                # 指定端口
                  tcpdump -i eth1 port 80
  
                  tcpdump -i eth1 tcp port 1024
 
                # 指定ip
  
                  tcpdump -i eth1 host 127.3.4.5
  
                  tcpdump -i eth1 src host 1.1.2.1 
                  tcpdump -i eth1 dst host 1.1.2.1
  
                  tcpdump -i eth1 scr host 1.1.2.1 and port 2046
  
iptables        #防火墙(慎用)
                 iptables -nvL 查看防火墙信息
                 # http://www.zsythink.net/archives/1199
                                
               # 禁用某个网卡的某端口
                     INPUT OUTPUT FORWARD                             
                      iptables -I INPUT -i eth0 -s 127.0.0.1 -p tcp --dport 25 -j DROP                                
               ### 表  filter nat mangle raw
                   链 INPUT OUTPUT FORWARD PREROUTING POSTROUTING                                
                                   
w               # w命令显示系统当前用户及其运行进程的信息
                
nohup           #不挂断的运行命令,注销后后台执行
                nohup command > myout.file 2>&1 &
                                                
iostat          #查看CPU使用情况、设备I/O信息、NFS设备信息
                
                某网卡增加IP:  # /etc/sysconfig/network-scripts 增加文件 ifcfg-eth1:X,然后重启network服务
                               # 文件内容
                                                    #IP Config for eth1:
                                                        DEVICE='eth1:1'
                                                        HWADDR=x0:8x:xa:1b:92:75
                                                        NM_CONTROLLED='yes'
                                                        ONBOOT=yes
                                                        IPADDR='122.209.15.2'
                                                        NETMASK='255.255.255.192'
                                                        GATEWAY='123.2.1.1'
                                # 重启  service network restart
        
badblock -v /dev/sda3 #检查磁盘坏道                                

fdisk -l 查看磁盘
                
mount      挂载
          #  mount /dev/sdb4 /old/        
        
umonut /mnt 取消挂载     
                 
mkfs   格式化磁盘

df -Th 查看文件系统类型
mkfs -t ext4 /dev/sdc    
               
     vi /etc/fstab                
     /dev/sdc              /data1                ext4    defaults        0 0 

14 远程连接, 文件传输:

ssh,    #   ssh huff@192.168.56.101 
        #   ssh username@ip [command]  在目标机器远程执行命令并返回命令结果,command要用双引号
        #   可通过ssh来安全传送文件,如将本地某文件压缩并传到远程主机并解压
          tar cf - youfile | ssh huff@192.168.56.101 "tar -C /home/huff xf -"

wget           # wget 'url' -O dest  将url上的文件写入本次dest
               # wget -m ftp://username:password@hostname

curl          # 和wget类似 支持上传和下载
              #显示ftp目录: 
                   curl ftp://183.60.115.62:53000/fun/log/20140717/ -u user:passwd
              #下载一个文件: 
                   curl ftp://183.60.115.62:53000/fun/log/20140717/ -u user:passwd -o test
              #显示http头信息
                   curl -i www.baidu.com
              #只显示http头信息
                   curl -I www.baidu.com
              #显示通信过程
                   curl -v www.baidu.com
              #显示相信请求内容并输出到文件
                   curl --trace output.txt www.baidu.com
              # 发送http post请求
                    curl -d "cc_id=364&world_id=8001" "www.baiud.api"

15 常用服务

httpd
rsync           #见上文
ftp             #ftp
                ftp>open ${ftp_ip} ${ftp_port}
                   >user $user  $password  
                   >cd $dir           #远程主机
                   >lcd ${local_dir}  #本地
                   > mget *           #下载
                   > close 
network
crontab   #  分 时 日 月 星 command
           特殊用法
           @reboot        Run once, at startup.
           @yearly        Run once a year, "0 0 1 1 *".
           @annually      (same as @yearly)
           @monthly       Run once a month, "0 0 1 * *".
           @weekly        Run once a week, "0 0 * * 0".
           @daily         Run once a day, "0 0 * * *".
           @midnight      (same as @daily)
           @hourly         Run once an hour, "0 * * * *". 

16 shell快捷键

ctrl + r:搜索history中的命令
ctrl + a:光标跳到行首
ctrl + e:光标跳到行尾
ctrl + w:删除光标前的一个单词
ctrl + k:删除光标后的所有字符
ctrl + u:删除光标前的所有字符
ctrl + y:恢复ctrl + w、ctrl + k、ctrl + u 删除的字符
ctrl + 光标 :在单词间移动

17 高级工具

gdb  程序调试工具
      gdb 程序名 core文件  输入bt参数调试
      gdb -q -batch -ex "set heigt 0" -ex "thread apply all bt full" zoned core

rpm 包安装
    rpm -ivh xxx.rpm    #安装rpm包
    rpm -qpi xxx.rpm    #查看包文件

18 shell规范

阅读《Shell脚本编码规范》

19 日志管理

logrotate  # 在/etc/logrotate.d/目录下添加日志监控文件
   
如:nginx
文件内容:
                           
/data/pboy/log/nginx/*.log {
                           daily
                           rotate 3
                           create 0664 user00 users
                           size=512M
                           missingok
                           notifempty
                           postrotate
                           /data/app/nginx/sbin/nginx -s reload
                           endscript
                           }
                                        
# 在crontab中添加任务
   0 4 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx

20 常用脚本开头示例

#!/bin/sh
SELF_PATH=$(readlink -f $0)
SELF_DIR=$(dirname $SELF_PATH)
SELF_NAME=$(basename $SELF_PATH)
IPLIST=${SELF_DIR}/pboy_ip.list                

21 awk专区

判断日志时间

start_utime=$(date +'%s' -d '5 minutes ago')
find ${LOG_PATH}  -mmin -5 -type f -name '*.*' -exec tail {} \;|awk -F'|' -v start=$start_utime '{gsub("[-|:]"," ",$1);t=mktime(substr($1,0,19));if(t>start)print substr($1,0,19),$2,$10,$11}'

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云服务器
云服务器(Cloud Virtual Machine,CVM)提供安全可靠的弹性计算服务。 您可以实时扩展或缩减计算资源,适应变化的业务需求,并只需按实际使用的资源计费。使用 CVM 可以极大降低您的软硬件采购成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档