Minthub.

Linux备忘

Word count: 3.2kReading time: 16 min
2024/12/12

写在开头

一些零散的Linux知识备忘,绝对不是想随便塞一些垃圾到博客里

Unix

Command

options

  • toggle: on/off
  • options: need information

ls

  • -a: show all files
  • -o/-l: long/longer listing
  • -d: directory
  • -f: decorate names
  • -ot: sorts by modification time

man

info

cat

less more

read files, h for help, q to quit

od

viewing raw data in octal, hex, control chats. Looking for non-printing characters in codes.

cp/mv

-i to ask before overwrite

cp -r to remove directory

tar

  • -c: 产生新的包
  • -f: 指定名字
  • -r: 增加文件
  • -u: 更新文件
  • -t: 列出文件
  • -x: 解开文件
  • gzip
    • -czf: 压缩
    • -xzf: 解压

filters

  • head/tail: show first/last n lines/chars(-n/-c) of files
  • grep: searching using regular expressions grep options pattern [files]
    • -i:忽略大小写进行匹配
    • -v:反向查找,只打印不匹配的行
    • -n:显示匹配行的行号
    • -r:递归查找子目录中的文件
    • -l:只打印匹配的文件名
    • -c:只打印匹配的行数
  • sort: sort input lines by lexically or ornumerically
    • -n: 按照数值排序
    • -r: 倒序
    • -o: 将结果存储
    • -k n: 按照第n列的值重排
  • uniq: remove identical, adjacent lines(using with sort)
    • -c或--count 在每列旁边显示该行重复出现的次数
    • -d或--repeated 仅显示重复出现的行列
    • -u或--unique 仅显示出一次的行列
  • wc: Word count (line count,character count), (line, word, char)
    • -c或--bytes或--chars 只显示Bytes数
    • -l或--lines 只显示行数
    • -w或--words 只显示字数
  • cut: Select fields of a line [https://www.cnblogs.com/Spiro-K/p/6361646.html]
  • tr: translate tr [OPTION]…SET1[SET2]
    • -c, --complement:反选设定字符。也就是符合 SET1 的部份不做处理,不符合的剩余部份才进行转换
    • -d, --delete:删除指令字符
    • -s, --squeeze-repeats:缩减连续重复的字符成指定的单个字符
    • -t, --truncate-set1:削减 SET1 指定范围,使之与 SET2 设定长度相等
du -sh

Disk usage summary, human readable

permissions

  • permissions
    • r - read
    • w - write
    • x - execute
  • entities
    • user
    • group
    • other
  • chmod
    • rwxrwxrwx

    • r - 4

    • w - 2

    • x - 1

    • [u/g/o/a] [+-=] [rwx]

Basic Vim

  • k: up
  • j: down
  • h: left
  • l: right
  • b: left a word
  • w: right a word
  • 0: beginning of line
  • $: end of line
  • db: delete word back
  • dw: delete word forward
  • d$: kill to end of line
  • /: search

Shell

IO

  • stdin: fd 0
  • stdout: fd 1
  • stderr: fd 2

Variables

  • USER: list of directories searched by shell for disk utilities
  • SHELL: The login shell
  • $$: the PID of current shell
  • $?: the return value of the last command
  • $# The number of arguments
  • $* All arguments
  • $@ All arguments(individually quoted)
  • ${n} The nth positional argument
  • TERM: Terminal type

$( cmd ) / 'cmd'

 to inhibit metacharacter, connect lines too
to start new line
" will inhibit all but  ' $
' will inhibit all, can't contain '

echo -e allow expansion of escape chars

Process & Jobs

  • process: ps -f(full) -e(all) / kill
  • jobs:
    • & after a command make it run in the background
    • ^Z to suspend the process in the foreground
    • fg bring the most recent process back to the foreground
    • bg to put the most recently suspended process into the background

Command Sequence

  • cmd1; cmd2; cmd3
  • grounped commands: {cmd1; cmd2; cmd3} > out
  • grounped commands in subshell: cmd1; (cmd2; cmd3); cmd4

Conditional Operators

  • cmd1 && cmd2: cmd1 execute first, if cmd1 succeeds, cmd2 execute
  • cmd1 || cmd2: cmd1 execute first, only if cmd1 fails cmd2 execute

Vim

Vim 的三种模式

  1. 普通模式 (Normal Mode)
    • 默认进入 Vim 的模式,用于导航和执行命令。
    • 通过按 ESC 返回普通模式。
  2. 插入模式 (Insert Mode)
    • 用于输入和编辑文本。
    • 在普通模式下按 i(插入光标左侧)或 a(插入光标右侧)进入插入模式。
  3. 命令模式 (Command Mode)
    • 用于保存、退出或执行其他全局操作。
    • 在普通模式下按 :进入命令模式。

基本操作

启动和退出

  • 启动:在终端输入 vim 文件名 打开文件(若文件不存在,将创建一个新文件)。
  • 退出
    • :w 保存文件。
    • :q 退出 Vim。
    • :wq 保存并退出。
    • :q! 强制退出(不保存)。

导航

  • 字符/行导航
    • h 左移一个字符。
    • l 右移一个字符。
    • j 下移一行。
    • k 上移一行。
  • 单词导航
    • w 跳到下一个单词的开头。
    • e 跳到当前/下一个单词的结尾。
    • b 跳到当前/前一个单词的开头。
  • 行内导航
    • 0 移动到行首。
    • ^ 移动到行首非空白字符。
    • $ 移动到行尾。
  • 页面导航
    • Ctrl-d 向下滚动半页。
    • Ctrl-u 向上滚动半页。
    • Ctrl-f 向下滚动一页。
    • Ctrl-b 向上滚动一页。
  • 跳转到指定行
    • :数字 跳转到指定行,如 :10 跳到第10行。
    • gg 跳到文件开头。
    • G 跳到文件结尾。

编辑

  • 插入模式
    • i 在光标前插入。
    • I 在行首插入。
    • a 在光标后插入。
    • A 在行尾插入。
    • o 在当前行下方插入新行。
    • O 在当前行上方插入新行。
  • 删除
    • x 删除当前字符。
    • dd 删除当前行。
    • d$ 删除从光标到行尾。
    • d^ 删除从光标到行首。
  • 复制/粘贴
    • yy 复制当前行。
    • p 在光标后粘贴。
    • P 在光标前粘贴。
  • 替换
    • r 替换当前字符。
    • R 进入替换模式。
  • 撤销/重做
    • u 撤销上一步操作。
    • Ctrl-r 重做。

搜索与替换

  • 搜索
    • /关键字 搜索关键字,按 n 跳到下一个,N 跳到上一个。
    • ?关键字 向上搜索关键字,按 n 跳到下一个,N 跳到上一个。
  • 替换
    • :s/旧文本/新文本 替换当前行的第一个匹配。
    • :s/旧文本/新文本/g 替换当前行的所有匹配。
    • :%s/旧文本/新文本/g 替换整个文件的所有匹配。
    • :%s/旧文本/新文本/gc 替换时逐一确认。

多文件操作

  • 打开多个文件
    • vim file1 file2 同时打开多个文件。
    • :n 切换到下一个文件。
    • :prev 切换到上一个文件。
    • :q 关闭当前文件。
  • 分屏操作
    • :split file 水平分屏打开文件。
    • :vsplit file 垂直分屏打开文件。
    • Ctrl-w w 切换屏幕。

宏与重复

  • 录制宏
    • q键名 开始录制宏,如 qa 录制到寄存器 a。
    • 执行编辑操作。
    • q 停止录制。
    • @键名 执行宏。
  • 重复操作
    • . 重复上一次普通模式的命令。

配置

  • 设置选项
    • :set nu 显示行号。
    • :set nonu 取消显示行号。
    • :set hlsearch 高亮搜索结果。
    • :set nohlsearch 取消高亮。
    • :set tabstop=4 设置Tab宽度为4。
  • 保存配置
    • 将配置写入 ~/.vimrc 文件,以便每次启动 Vim 自动加载。

快捷键总结

  • ESC:返回普通模式。
  • :w 保存,:q 退出。
  • h/j/k/l:光标移动。
  • i 进入插入模式。
  • / 搜索关键字。
  • dd 删除行,yy 复制行,p 粘贴。
  • u 撤销,Ctrl-r 重做。

Bash

Script

#!/bin/bash - sha-bang

  • [ expr ] whitespace around the [] are necessary
    • -z true if string is empty

    • -n true if string is not empty

    • -e file True if file exists

    • -d file True if file is a directory

    • -f file True if file is a regular file

    • -L file True if file is a symbolic link

    • -r file True if file is readable by you

    • -w file True if file is writable by you

    • -x file True if file is executable by you

    • -O file True if file is effectively owned by you

    • f1 -nt f2 True if f1 is newer than f2

    • f1 -ot f2 True if f1 is older than f2

    • f1 -ef f2 True if f1 is a hard link to f2 (they are the same file)

    • arithmetic test, using -lt -le -eq -ne -ge -gt

    • logical operators:

      • ! expr: NOT
      • exp1 -a exp2: AND
      • exp1 -o exp2: OR
  • [[ ]]
    • logical operators: ! && ||
    • ==/!=: treat the right as a pattern
    • =~: treat right as an extended regular expression
  • (()) - let
    • treats values stored in parameters as intergers

    • allows to evaluate relational experssions

    • ~ 按位取反(NOT) 对每一位取反,0 变为 1,1 变为 0

    • << 左移 将二进制位向左移动指定的位数,右侧补 0

    • >> 右移 将二进制位向右移动指定的位数,左侧补 0 或符号位(取决于具体实现)

    • ^ 按位异或(XOR) 如果两个对应位不同,结果为 1,否则为 0

    • & 按位与(AND) 如果两个对应位都为 1,结果为 1,否则为 0

    • 按位或(OR) 如果两个对应位有一个为 1,结果为 1,否则为 0
    • interger literals

      • dec: ddd
      • oct: 0dd
      • hex: 0xdd

Control Structures

  • if tests; then cmds; fi

  • if tests; then cmds; else cmds; fi

  • if tests; then cmds; elif tests; then cmds; else cmds; fi

  • while tests; do cmds; done

  • for name in [list]; do cmds; done

  • for (( i=0; i<n; ++i )); do # c like loop

  • break to exit, continue to skip

  • case word in {pattern ) cmds ;;} esac

  • select name in [list]; do cmds; done

  • use read to preserve spaces

  • for f in $(ls -1); do # if filename have spaces, it will not be preserve

  • ls -1 | while read f; do # space will be preserve

  • Brace Expansion: {x..y[..inc]}

    • {5..13}
    • {a..g}
    • useful in for loop

Arguments

  • $0 is the name of the command

  • $$: the PID of current shell

  • $?: the return value of the last command

  • $# The number of arguments

  • $* All arguments

  • $@ All arguments(individually quoted)

  • ${n} The nth positional argument

  • shift [cnt]: default 1, shift args to the left cnt positions, $1 is gone, $2->$1

  • getopts: getopts optstring name

    • 只支持短选项

    • optstring开头添加:禁用错误输出

    • 选项后添加:表示需要参数

    • 按照命令行参数的顺序解析选项,非选项的参数会留在 $@ 中

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      #!/bin/bash

      while getopts "ab:cC" opt; do
      case $opt in
      a ) echo "option a, at index $OPTIND";;
      b ) echo "option b with arg = $OPTARG, at index $OPTIND";;
      c |C ) echo "option $opt,at index $OPTIND";;
      ? ) echo "usage:$0[-a] [b arg][-c]args..." ;exit 1;;
      esac
      done

      echo "\$OPTIND = $OPTIND"
      shift $(($OPTIND - 1)) # shift off the options

      echo -e "\nHere are the remaining arguments:"
      for i in "$@" ; do
      echo -e "\t$i"
      done

Functions

  • function name {body}

  • name () {body}

  • export -f funcname to make it available to subshells

  • like script, $1, $2, shift, $#, $*, $@ work the same

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    function hello
    {
    echo "hello $1"
    if [[ -n "$2" && "$2"-gt 1 ]] ; then
    hello $1 $(($2-1))
    fi
    }

    $ hello Vera 3
    > helloVera
    > helloVera
    > helloVera

  • local Variables: local {var}

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    function hello{
    local USER=’Elmer Fudd’
    FOO=’Hunting Wabbit’
    echo "Hello, $USER, you are $FOO"
    }

    $ FOO=’Baking Cookies’
    $ echo $USER
    > kschmidt
    $ hello
    > Hello, Elmer Fudd, you are Hunting Wabbit
    $ echo $FOO
    > Hunting Wabbit
    $ echo $USER
    > kschmidt

Parameter Expansion

  • Unset or Null Parameters
    • ${param :-word} Use word if param is not set or is null

    • ${param :=word} Use word if param is not set or is null, set it to word

    • ${param :?word} If param is not set or is null, print word to stderr, exit shell (if not interactive)

    • ${param :+word} If param is set, use word, otherwise use null

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      $ unset foo
      $ echo ${foo:-"Hello!"}
      > Hello!
      $ echo $foo
      >
      $ echo ${foo:?"Houston, we have a problem"}
      > bash: foo: Houston, we have a problem
      $ echo ${foo:+"We here?"}
      >
      $ echo ${foo:=’I am de Fault’}
      > I am de Fault
      $ echo $foo
      > I amde Fault
      $ echo ${foo:?"Houston, we have a problem"}
      > I amde Fault
      $ echo ${foo:+"We here?"}
      > Wehere?
  • Removing Patterns
    • ${param#pattern} Remove shortest leading pattern

    • ${param##pattern} Remove longest leading pattern

    • ${param%pattern} Remove shortest trailing pattern

    • ${param%%pattern} Remove longest trailing pattern

      1
      2
      3
      4
      5
      6
      7
      8
      9
      $ f=a^b^c
      $ echo ${f#*^}
      > b^c
      $ echo ${f##*^}
      > c
      $ echo ${f%%^*}
      > a
      $ echo ${f%^*}
      > a^b
  • Pattern Substitution
    • ${param/pattern/string} replace first match

    • ${param//pattern/string} replace all match

      1
      2
      3
      4
      5
      $ f="The cat sat on the hat"
      $ echo ${f/[hcs]at/XXX}
      > The XXX sat on the hat
      $ echo ${f//[hcs]at/XXX}
      > The XXX XXX on the XXX
  • Substrings
    • ${param:offset}

    • ${param:offset:length}

      1
      2
      3
      4
      5
      $ n=’Kurt Schmidt’
      $ echo ${n:3}
      > t Schmidt
      $ echo ${n:5:3}
      > Sch
  • Change Case
    • ${parampattern} ^ covert ot upper, , convert to lower

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      $ f=SHOUT
      $ echo ${f,} # If pattern is missing, treated as a ?
      > sHOUT
      $ echo ${f,,} # , for first, ,, for each
      > shout
      $ echo ${f,[SOT]}
      > sHOUT
      $ echo ${f,,[SOT]}
      > sHoUt
      $ f=quiet
      $ echo ${f^^} # ^ for first, ^^ for each
      > QUIET

AWK

  • awk '{print $3}' input.txt
  • awk -f script.awk input.txt
  • #!/usr/bin/awk -f

form of a AWK program

pattern {action}

  • pattern – Text.Numeric or string relational operator, or regular expression match
    • If empty, actions are applied to every record
  • action – Statement or sequence of statements
    • If empty, default action is to print the entire line

patterns

  • Any numeric or string relational operator

  • Logical operators (&&, ||, !)

  • regular expression (delimited by / /)

  • special patterns:

    • BEGIN: True before first record is parsed
    • END: True after last record is parsed
  • Empty test applies to every record

    1
    2
    3
    awk 'BEGIN { print "Processing starts..." }
    { print "Line:", $0 }
    END { print "Processing ends." }' file.txt
  • describe a range

    • NR==8, NR==165, print lines 8 through 165, inclusive
    • /<body>/, /<\/body>/, print first line with and every line until next

actions

  • default action is to print entire record ($0)

language

C-like syntax

  • fields: default split over whitespace, identified by $1, $2 ... $NF. $0 is the entire line
  • variable: dynamic typing. There are some built-in var:
    • NF: Number of fields in current record
    • NR: Number of records read (so far)
    • FNR: Number of records read in this file (the line #)
    • FS: Input field separator
    • OFS: Output field separator
    • RS: Input record separator
    • ORS: Output record separator

String Concatenation

simply juxtaposition, parantgeses will be helpful

  • $ awk ’BEGIN{print -12 " " (-24) }’
  • print "And I’m spinning..." > (a b)

String Functions

  • length

  • tolower

  • toupper

  • index: 返回子串第一次出现的索引

  • substr: 返回子串

  • sub: 替换第一个匹配的部分

  • gsub: 替换所有

  • gensub: 替换的n个匹配部分

  • split: 根据正则分割字符串成数组

  • patsplit: 将匹配成功的部分放入数组

  • sprintf: 返回格式化的字符串,类似printf

  • strtonum: 从字符串中提取数值

Arrays

  • All arrays are associative (dictionary in fact)

  • key can be num or str

  • vectors can be sparse

  • indices can be negative

  • delete: delete a[2]

  • awk support multidimensional arrays: a[i, j] = i*j

  • sorting array (Gawk)

    • asort - sort the value asort(array [, dest])
    • asorti - sort the key asorti(array [, dest])
  • numeric sorting: PROCINFO["sorted_in"] = val_num_asc

Function

1
2
3
4
function func_name([param_list])
{
body
}

AWK One-Liners

  • line count: awk 'END {print NR}'
  • like grep: awk '/regex/'
  • like head: awk 'FNR<=10'
  • add line numbers: awk '{print FNR, $0}' or awk '{printf("%03d %s\n", FNR, $0)}'
  • print line 12-23, inclusive: awk 'FNR==12, FNR==23'
  • remove black lines: awk 'NF>0'
  • double-space a file: awk '1; {print "}'
  • smarter double-space: awk 'NF>0 {print $0 "\n"}'
  • remove leading whitespace from each line: awk '{sub(/^[ \t]+$/, ")}; 1'

Regular Expressions

egrep regex files (awk)

Syntax

  • primitive operation
    • c: any literal char
    • r*: 0 or more
    • r1r2: concatenation
    • r1|r2: r1 or r2
    • (r): grouping
  • sugar
    • . match any single char
    • ? 0/1
      • 1 or more
    • [...] match any single chars in the brackets
    • [^...] inverted
    • ^ beginning of line
    • $ end of line
    • < > word anchors
  • nickname
    • numeric digit
    • word char, num or _
    • whitespace
CATALOG
  1. 1. 写在开头
  2. 2. Unix
    1. 2.1. Command
      1. 2.1.1. options
      2. 2.1.2. ls
      3. 2.1.3. man
      4. 2.1.4. info
      5. 2.1.5. cat
      6. 2.1.6. less more
      7. 2.1.7. od
      8. 2.1.8. cp/mv
      9. 2.1.9. tar
      10. 2.1.10. filters
        1. 2.1.10.1. du -sh
      11. 2.1.11. permissions
      12. 2.1.12. Basic Vim
    2. 2.2. Shell
      1. 2.2.1. IO
      2. 2.2.2. Variables
      3. 2.2.3. Process & Jobs
      4. 2.2.4. Command Sequence
      5. 2.2.5. Conditional Operators
  3. 3. Vim
    1. 3.1. Vim 的三种模式
    2. 3.2. 基本操作
      1. 3.2.1. 启动和退出
    3. 3.3. 导航
    4. 3.4. 编辑
    5. 3.5. 搜索与替换
    6. 3.6. 多文件操作
    7. 3.7. 宏与重复
    8. 3.8. 配置
    9. 3.9. 快捷键总结
  4. 4. Bash
    1. 4.1. Script
    2. 4.2. Control Structures
    3. 4.3. Arguments
    4. 4.4. Functions
    5. 4.5. Parameter Expansion
    6. 4.6. AWK
      1. 4.6.1. form of a AWK program
      2. 4.6.2. patterns
      3. 4.6.3. actions
      4. 4.6.4. language
      5. 4.6.5. String Concatenation
      6. 4.6.6. String Functions
      7. 4.6.7. Arrays
      8. 4.6.8. Function
      9. 4.6.9. AWK One-Liners
    7. 4.7. Regular Expressions
      1. 4.7.1. Syntax