当前位置: 首页 > 工具软件 > shell-tricks > 使用案例 >

Shell tricks

白坚壁
2023-12-01

1. bash支持关联数组(到了这么复杂的程度,用python吧):

declare -A map # define an associated array (hash map), this is supported by bash >= 4.1.2
map[k1]=v1; map[k2]=v2;
echo ${map[k1]} #v1
${!a[@]} # the keys in the associated array/list, * also works by replacing @
${a[@]} # the values in the associated array/list
${#a[@]} # the number of elements in the associated array/list
unset map[k1]

2. 数学运算要放在(())中

(( a++ ))
echo $(( a++ ))
if (( a++ > 4)); then echo greater than 4 ; fi

3. string to list

str="a b c"; list=($str); # transform a string to a list separated by $IFS
echo ${list[0]} # a
set -- $str ; echo $1 # a
result=$(echo hello) <=> result=`echo hello` # but the former support embed

4. 循环

for i in {0..23}; do echo $i ; done
for i in `seq 0 23`; do echo $i; done
for k in ${!map[*]}; do echo $k ; done

nums="1 2 3" ; for n in $nums ; do echo $n ; done # splited by $IFS

OIFS=$IFS; IFS=b; # if IFS is assigned to a string
IFS=$'\x61\x62' # a or b as the spliter
nums="3b4b56b";
for n in $nums; do echo $n ; done

5. 正则表达式

if [[ "$role_info" =~ "slave" ]] ; then echo This is a slave; fi
expr match "$myself" .*connected$

6. 一些命令

echo -n "Hello" | od -tx1 -An | sed 's/ /%/g' # url encoder
grep -v -F -f pattern.dat <(cat Hello.txt) # grep lines from Hello.txt that does not contains patterns in pattern.dat
join -o 1.2 -o 1.1 -o 1.3 -o 1.4 -o 2.2 -1 2 -2 1 -e -1 -a 1 <(sort -k 2 req) <(awk -F, '{print $1,$8}' cpr.csv | sort -k 1 ) | join -a 1 - <(awk -F, '{print $1,$4}' 10s.csv | sed 's/"//g'| sort ) # join是个神奇的命令,可以按照某一列作为key进行拼接,并且支持inner/left/right/full join,支持输出哪些字段,但是前提是key必须是排序的,结合sort和awk,棒极了

7. 更多字符串操作:linux shell 字符串操作详解 (长度,读取,替换,截取,连接,对比,删除,位置 ) - gaomatlab - 博客园

8. () 和 {}

value=5; ( value=10; sleep 5 ) ; echo $value; // 5 创建子进程,前台执行
value=5; ( value=10; sleep 5 )& echo $value; // 5 创建子进程,后台执行
value=5; { value=10; sleep 5 ; } ; echo $value; // 10, {}不会打开子shell,没有创建子进程
value=5; { value=10; sleep 5 ; } & echo $value; wait; echo $value // 5 5 {} & 和 ()&几乎没有区别,创建子进程,后台执行

9. 配置代理

export ALL_PROXY="socks5://localhost:9987"
export http_proxy="socks5h://localhost:9987"
export https_proxy="socks5h://localhost:9987"

10. 颜色

echo '\033[31mhello\033[0m' # a red hello
print '\033[31mhello\033[0m'
# or when print messages on console for any programming language 

11. 随机数

echo $RANDOM #产生0-32768之间的随机整数
# 如何产生正态分布的数?根据大数定律,可以通过多个数的均值来近似

 类似资料:

相关阅读

相关文章

相关问答