首页 > 数据库 > 数据库开发技术 > Shell脚本优化使用技巧(二)
先放个链接,万一有人关注呢
↓ ↓ ↓ ↓ ↓
8、使用正确的命令行选项:很多命令都有一些选项可以使用,可以根据具体需求选择合适的选项来提高执行效率。
示例:使用sort命令的-b选项来忽略空格。
# 不优化版本cat input.txt | tr -d " " | sort | uniq# 优化版本cat input.txt | sort -b | uniq
# 不优化版本for i in $(seq 1 1000)doresult=$(expr $i \* 2)echo $resultdone# 优化版本declare -A cachefor i in $(seq 1 1000)doif [[ ${cache["$i"]} ]]thenresult=${cache["$i"]}elseresult=$(expr $i \* 2)cache["$i"]=$resultfiecho $resultdone
10、尽量避免使用外部命令:在脚本中使用外部命令会导致额外的进程调用,从而降低脚本的性能。可以使用内置的命令或者将外部命令封装为函数来避免过多的外部命令调用。
示例:避免使用外部命令。
# 不优化版本for file in *.txtdowc -l $filedone# 优化版本for file in *.txtdoline_count=$(grep -c "^" $file)echo "$line_count $file"done
# 不优化版本for file in *.txtdoprocess_file $filedone# 优化版本ls *.txt | parallel process_file {}
# 不优化版本if [[ $VAR == "value1" ]] || [[ $VAR == "value2" ]] || [[ $VAR == "value3" ]]thenecho "matched"fi# 优化版本if [[ $VAR == "value1" ]] \|| [[ $VAR == "value2" ]] \|| [[ $VAR == "value3" ]]thenecho "matched"fi
# 不优化版本if [[ $VAR1 == "value1" ]]thenecho "matched"fiif [[ $VAR2 == "value2" ]]thenecho "matched"fi# 优化版本function match() {if [[ $1 == $2 ]]thenecho "matched"fi}match $VAR1 "value1"match $VAR2 "value2"
# 不优化版本for file in *.txtdosed "s/foo/bar/g" $file > $file.tmpmv $file.tmp $filedone# 优化版本for file in *.txtdosed "s/foo/bar/g" $file > $file.tmpdonemv *.tmp .
# 不优化版本cat input.txt | grep "keyword" | awk '{print $1}'# 优化版本awk '/keyword/ {print $1}' input.txt
结束!
如有不足之处,欢迎指正!
谢谢你这么好看还关注我

原文作者:运维book思议;如有侵权,请联系管理员删除。