shell programming sheat sheet for myself

本文详细解析Shell脚本中数值计算、循环、条件判断、sed文本编辑工具等核心语法,提供实用的cheatsheet,帮助开发者快速掌握Shell编程技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

语法总是记不牢,文字记录之,搞个cheat sheet,自己用。。

1. 数值计算
a=0; (( a = a +1 )); echo $a

2. for循环
for f in `ls`; do echo $f; done

3. while循环

a=0; while [ $a -lt 10 ]; do echo -n "$a "; (( a = a+1 )); sleep 1; done ; echo;
a=0; while (( a < 10 )); do echo -n "$a "; (( a = a +1 )); sleep 1; done ; echo;

4. if判断
if [ -d /usr/local/bin ] ; then echo "directory exists."; else echo "directory not exists."; fi
if test -d /usr/local/bin; then echo "directory exists."; else echo "directory not exists."; fi
[ -d /usr/local/bin ] && echo "directory exists"
[ -d /user/local/bin ] || echo "directory not exists"

# for integers
num1 -eq num2 True if num1 equals num2.
num1 -ne num2 True if num1 is not equal to num2.
num1 -lt num2 True if num1 is less than num2.
num1 -gt num2 True if num1 is greater than num2.
num1 -le num2 True if num1 is less than or equal to num2.
num1 -ge num2 True if num1 is greater than or equal to num2.

# for string
str1 = str2 True if str1 and str2 are identical.
str1 != str2 True if str1 and str2 are not identical.
-n str1 True if str1 is not null (length is greater than zero).
-z str1 True if str1 is null (length is zero).

# for file conditions
-f somefile True if somefile exists and is an ordinary file.
-d somefile True if somefile exists and is a directory.
-s somefile True if somefile contains data (the size is not zero).
-r somefile True if somefile is readable.
-w somefile True if somefile is writable.
-x somefile True if somefile is executable.

# logical operators
cond1 -a cond2 True if both cond1 and cond2 are true.
cond1 -o cond2 True if either cond1 or cond2 is true.
! cond1 True if cond1 is false.


5. sed

sed 's/one/two/g' < in.file.txt > out.file.txt
sed -r 's/[0-9]{3,}//g' < in.file.txt <-- 注1
sed 's:old:new:g' < in.file.text > out.file.txt <-- 注2
sed -r 's/[0-9]{3,}/(&)/g' < sed.txt
sed -r 's/([0-9]+)\s+([a-z]+)/\2 \1/g' < sed.txt <-- 注3
sed -n -r '/\S+/p' < sed.txt <-- 注4
sed -r '/^$/d' < sed.txt
sed -n -r 's/([0-9]+)\s+([a-z]+)/\2 \1/gpw test.txt' < sed.txt <-- 注5
sed -r -e 's/([0-9]+)\s+([a-z]+)/\2 \1/g' -e '/^$/d' < sed.txt <--注6

注1: -r参数启用extended regular expression,原来自带的太弱了,而且要记好几套正则表达式很烦,干脆只要用到正则表达式的地方都启用扩展的,比如grep -E "[0-9]+"
注2: 分割符号可以是 / , : , _ , |
注3: 如果不启用-re那么'('还得写成'\(',很恶心
注4: sed默认会打印每一行(不论有没匹配),-n表示默认不打印,后面的p表示如果匹配了那执行打印该行,整行意思是打印非空的行
注5: /p 答应 /g 全局 /w file 结果写到文件,可以组合多个command
注6: 多条sed指令用-e分开
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值