全宇宙最全的bash 脚本常见用法总结!
用法示例: $ reverse_array 1 2 3 4 5 5 4 3 2 1 $ arr=(red blue green) $ reverse_array "${arr[@]}" green blue red
删除重复的数组元素创建临时关联数组。设置关联数组 CAVEAT:需要 示例功能: remove_array_dups() { # Usage: remove_array_dups "array" declare -A tmp_array for i in "[email?protected]"; do [[ $i ]] && IFS=" " tmp_array["${i:- }"]=1 done printf ‘%sn‘ "${!tmp_array[@]}" }
用法示例: $ remove_array_dups 1 1 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 5 1 2 3 4 5 $ arr=(red red green blue blue) $ remove_array_dups "${arr[@]}" red green blue
随机数组元素示例功能: random_array_element() { # Usage: random_array_element "array" local arr=("[email?protected]") printf ‘%sn‘ "${arr[RANDOM % $#]}" }
用法示例: $ array=(red green blue yellow brown)
$ random_array_element "${array[@]}" yellow # Multiple arguments can also be passed. $ random_array_element 1 2 3 4 5 6 7 3
循环一个数组每次 arr=(a b c d)
cycle() { printf ‘%s ‘ "${arr[${i:=0}]}" ((i=i>=${#arr[@]}-1?0:++i)) }
在两个值之间切换这与上面的工作方式相同,这只是一个不同的用例。 arr=(true false) cycle() { printf ‘%s ‘ "${arr[${i:=0}]}" ((i=i>=${#arr[@]}-1?0:++i)) }
LOOPS循环一系列数字替代 # Loop from 0-100 (no variable support). for i in {0..100}; do printf ‘%sn‘ "$i" done
循环遍历可变数字范围替代 # Loop from 0-VAR. VAR=50 for ((i=0;i<=VAR;i++)); do printf ‘%sn‘ "$i" done
循环数组arr=(apples oranges tomatoes)
# Just elements. for element in "${arr[@]}"; do printf ‘%sn‘ "$element" done
循环遍历带索引的数组arr=(apples oranges tomatoes)
# Elements and index. for i in "${!arr[@]}"; do printf ‘%sn‘ "${arr[i]}" done # Alternative method. for ((i=0;i<${#arr[@]};i++)); do printf ‘%sn‘ "${arr[i]}" done
循环遍历文件的内容while read -r line; do printf ‘%sn‘ "$line" done < "file"
循环遍历文件和目录不要用 # Greedy example. for file in *; do printf ‘%sn‘ "$file" done # PNG files in dir. for file in ~/Pictures/*.png; do printf ‘%sn‘ "$file" done # Iterate over directories. for dir in ~/Downloads/*/; do printf ‘%sn‘ "$dir" done # Brace Expansion. for file in /path/to/parentdir/{file1,file2,subdir/file3}; do printf ‘%sn‘ "$file" done # Iterate recursively. shopt -s globstar for file in ~/Pictures/**/*; do printf ‘%sn‘ "$file" done shopt -u globstar
文件处理CAVEAT:? 将文件读取为字符串替代 file_data="$(<"file")"
将文件读取到数组(按行)替代 # Bash <4 IFS=$‘n‘ read -d "" -ra file_data < "file" # Bash 4+ mapfile -t file_data < "file"
获取文件的前N行替代 CAVEAT:需要 示例功能: head() { # Usage: head "n" "file" mapfile -tn "$1" line < "$2" printf ‘%sn‘ "${line[@]}" }
用法示例: $ head 2 ~/.bashrc
# Prompt PS1=‘? ‘ $ head 1 ~/.bashrc # Prompt
获取文件的最后N行替代 CAVEAT:需要 示例功能: tail() { # Usage: tail "n" "file" mapfile -tn 0 line < "$2" printf ‘%sn‘ "${line[@]: -$1}" }
用法示例: $ tail 2 ~/.bashrc # Enable tmux. # [[ -z "$TMUX" ]] && exec tmux $ tail 1 ~/.bashrc # [[ -z "$TMUX" ]] && exec tmux
获取文件中的行数替代 示例函数(bash 4): lines() { # Usage: lines "file" mapfile -tn 0 lines < "$1" printf ‘%sn‘ "${#lines[@]}" }
示例函数(bash 3): 此方法使用的内存少于 lines_loop() { # Usage: lines_loop "file" count=0 while IFS= read -r _; do ((count++)) done < "$1" printf ‘%sn‘ "$count" }
用法示例: $ lines ~/.bashrc 48 $ lines_loop ~/.bashrc 48 计算目录中的文件或目录这是通过将glob的输出传递给函数然后计算参数的数量来实现的。 示例功能: count() { # Usage: count /path/to/dir/* # count /path/to/dir/*/ printf ‘%sn‘ "$#" }
用法示例: # Count all files in dir. $ count ~/Downloads/* 232 # Count all dirs in dir. $ count ~/Downloads/*/ 45 # Count all jpg files in dir. $ count ~/Pictures/*.jpg 64
创建一个空文件替代 # Shortest. >file # Longer alternatives: :>file echo -n >file printf ‘‘ >file
提取两个标记之间的线条示例功能: extract() { # Usage: extract file "opening marker" "closing marker" while IFS=$‘n‘ read -r line; do [[ $extract && $line != "$3" ]] && printf ‘%sn‘ "$line" [[ $line == "$2" ]] && extract=1 [[ $line == "$3" ]] && extract= done < "$1" }
用法示例: # Extract code blocks from MarkDown file. $ extract ~/projects/pure-bash/README.md ‘```sh‘ ‘```‘ # Output here...
文件路径获取文件路径的目录名称替代 示例功能: dirname() { # Usage: dirname "path" printf ‘%sn‘ "${1%/*}/" }
用法示例: $ dirname ~/Pictures/Wallpapers/1.jpg /home/black/Pictures/Wallpapers/ $ dirname ~/Pictures/Downloads/ /home/black/Pictures/
获取文件路径的基本名称替代 示例功能: basename() { # Usage: basename "path" : "${1%/}" printf ‘%sn‘ "${_##*/}" }
用法示例: $ basename ~/Pictures/Wallpapers/1.jpg 1.jpg $ basename ~/Pictures/Downloads/ Downloads
变量使用变量分配和访问变量$ hello_world="value" # Create the variable name. $ var="world" $ ref="hello_$var" # Print the value of the variable name stored in ‘hello_$var‘. $ printf ‘%sn‘ "${!ref}" value
或者,在 $ hello_world="value" $ var="world" # Declare a nameref. $ declare -n ref=hello_$var $ printf ‘%sn‘ "$ref" value
根据另一个变量命名变量$ var="world" $ declare "hello_$var=value" $ printf ‘%sn‘ "$hello_world" value
ESCAPE序列与流行的看法相反,使用原始逃逸序列没有问题。使用 文字颜色注意:需要RGB值的序列仅适用于真彩色终端仿真器。
文字属性
光标移动
删除文本
参数扩展间接
替换
长度
扩张
案例修改
默认值
BRACE EXPANSION范围# Syntax: {<START>..<END>} # Print numbers 1-100. echo {1..100} # Print range of floats. echo 1.{1..9} # Print chars a-z. echo {a..z} echo {A..Z} # Nesting. echo {A..Z}{0..9} # Print zero-padded numbers. # CAVEAT: bash 4+ echo {01..100} # Change increment amount. # Syntax: {<START>..<END>..<INCREMENT>} # CAVEAT: bash 4+ echo {1..10..2} # Increment by 2.
字符串列表echo {apples,oranges,pears,grapes} # Example Usage: # Remove dirs Movies,Music and ISOS from ~/Downloads/. rm -rf ~/Downloads/{Movies,Music,ISOS}
有条件的表达文件条件
文件比较
可变条件
变量比较
算术运算符分配
算术
按位
合乎逻辑
杂
算术设置变量的语法更简单# Simple math ((var=1+2)) # Decrement/Increment variable ((var++)) ((var--)) ((var+=1)) ((var-=1)) # Using variables ((var=var2*arr[2]))
三元测试# Set the value of var to var2 if var2 is greater than var. # var: variable to set. # var2>var: Condition to test. # ?var2: If the test succeeds. # :var: If the test fails. ((var=var2>var?var2:var))
TRAPS陷阱允许脚本在各种信号上执行代码。在pxltrm(用bash编写的像素艺术编辑器)中,陷阱用于在窗口大小调整时重绘用户界面。另一个用例是在脚本退出时清理临时文件。 应该在脚本开头附近添加陷阱,以便捕获任何早期错误。 注意:有关信号的完整列表,请参阅 在脚本退出时做一些事情# Clear screen on script exit. trap ‘printf e[2Je[He[m‘ EXIT
忽略终端中断(CTRL + C,SIGINT)trap ‘‘ INT
对窗口调整大小做出反应# Call a function on window resize. trap ‘code_here‘ SIGWINCH
在每个命令之前做点什么trap ‘code_here‘ DEBUG
当shell函数或源文件完成执行时执行某些操作trap ‘code_here‘ RETURN
性能禁用Unicode如果不需要unicode,则可以禁用它以提高性能。结果可能会有所不同,但是neofetch和其他程序有明显改善。 # Disable unicode. LC_ALL=C LANG=C
已过时的语法家当用
# Right: #!/usr/bin/env bash # Wrong: #!/bin/bash
命令替换用 # Right. var="$(command)" # Wrong. var=`command` # $() can easily be nested whereas `` cannot. var="$(command "$(command)")"
功能声明不要使用 # Right. do_something() { # ... } # Wrong. function do_something() { # ... }
内部变量获取
|
- unix – 如何使用不同的字段分隔符对多个字段进行排序
- angular js 左右选择框 Freemarker+js
- 角度路径参数中的前向斜率
- angularjs – 如何从角度js中的json获取最小值和最大值
- scala – 为什么Source.fromIterator需要将Function0 [Iter
- 如何在我的.vimrc中使用变量?
- bash – 如何跳过$@中的第一个参数?
- angular – MdDatepickerModule – 欧洲格式
- WebService之Axis2快速入门(5): 管理会话(Session)
- Comparison--开发WebService两种开源工具CXF和Axis2的比较