shell 脚本小功能集合
Table of Contents
1 字符串处理
1.1 去掉空白
# 去前面空格 var="${var#"${var%%[![:space:]]*}"}" # 去后面空格 var="${var%"${var##*[![:space:]]}"}" # 去掉首尾空白 trim_string() { # Usage: trim_string " example string " : "${1#"${1%%[![:space:]]*}"}" : "${_%"${_##*[![:space:]]}"}" printf '%s\n' "$_" } $ trim_string " Hello, World " Hello, World # 整理参数 $ echo " aa bb " | xargs aa bb # 去掉所有空格 $ echo " a b c " | tr -d '[:space:]' abc$ # 去掉前面的空格 $ echo " a b c " | sed -e 's/^[[:space:]]*//' # 去掉后面的空格 $ echo " a b c " | sed -e 's/[[:space:]]*$//' # 去掉前后空格 echo " a b c " | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//'
1.2 大小写转换
echo "Upper to Lower" | tr '[:upper:]' '[:lower:]' # bash 4.0+ to lower echo "${a,,}" # bash 4.0+ to upper echo "${a^^}" # reverse case echo "${a~~}"
1.3 判断是否包含子串
if [[ $var == *sub_string* ]]; then printf '%s\n' "sub_string is in var." fi # Inverse (substring not in string). if [[ $var != *sub_string* ]]; then printf '%s\n' "sub_string is not in var." fi # This works for arrays too! if [[ ${arr[*]} == *sub_string* ]]; then printf '%s\n' "sub_string is in array." fi # start with sub-string: *sub_string # end with sub-string: sub_string* # using a case statement case "$var" *sub_string*) # Do ;; *) # Else esac
2 gdb
2.1 设置变量
# 设置变量 (gdb) set var i = 10 # 设置地址为值 (gdb) set set {int}0x1236252 = 10 # 设置寄存器 set var $eax = 10
2.2 字符串
# 打印 char str1[] = "abcd"; (gdb) x/s str1 # 打印 wchar_t str2[] = L"abcd"; (gdb) x/ws str2 # 设置字符串, 也可以通过 set{char [n]} 0xxxxx = "ABCD" (gdb) set main::str1 = "ABCD";
2.3 函数
# 正则搜索函数 (gdb) info functions pre[a-z]* # 退出函数 (gdb) fin # 执行函数 call func() print func() # 显示函数栈 (gdb) i frame # 显示寄存器 (gdb) i registers # 尾调用栈信息 (gdb) set debug entry-values 1 (gdb) i frame
2.4 断点
# 匿名空间设置断点 (gdb) b (anonymous namespace)::func # 地址上打断点 (gdb) b *0x22222 # 文件行号上打断点 (gdb) b file.c:17 # 保存/恢复断点 (gdb) save breakpoints file-name-to-save (gdb) source file-name-to-save (gdb) info breakpoints # 临时,一次性断点 tbreak (gdb) tb xxx.c:12 # 条件断点 (gdb) b xxx.c:10 if i==10 # 忽略断点 1 一共 10 次 (gdb) ignore 1 10
2.5 观察点
# 设置观察点,变量变化时停下来 (gdb) watch var1 (gdb) watch *(int*)0x33333 # 令观察点只对特定线程生效 (gdb) wa var1 thread 3 # 读观察点,读取变量时生效 (gdb) rwatch var1 # 读写观察点 (gdb) awatch var1
2.6 打印内存
# 16 进制打印 10个字节 (gdb) x/10xb a # 10 进制打印 (gdb) x/20ub a # 2 进制打印 (gdb) x/16tb a