本文收集了一堆的shell脚本技巧,我说过,我写博客主要是作一些学习笔记,方便自己查阅,所以,我会搞出这么一篇文章,也没有什么不可理解的。关于这些技巧的出处,诶,我也忘了,可能来自theunixschool、 commandlinefu、酷勤网和igigo.net,当然了,也有部分是我自己的经验心得,管他呢,进了我的脑子就是我的了。
0. shell 调试
在somefile.sh 文件里加上set+x set-x
1. 用 && || 简化if else
if [[ 0 == $? ]]; then
echo "good zip"
else
echo "bad zip"
fi</div>
可以简化为:
2. 判断文件非空
echo "not empty"
fi</div>
3. 获取文件大小
stat --printf='%s\n' $file
wc -c $file</div>
4. 字符串替换
a='a,b,c'
echo ${a//,/ /}
5. Contains 子字符串?
string="My string"
if [[ $string == *My* ]]; then
echo "It's there!"
fi</div>
6. rsync备份
rsync -r -t -v /source_folder [user@host:/destination_folder
</div>
7. 批量重命名文件
为所有txt文件加上.bak 后缀:
去掉所有的bak后缀:
把所有的空格改成下划线:
把文件名都改成大写:
8. for/while 循环
for ((i=0; i < 10; i++)); do echo $i; done
for line in $(cat a.txt); do echo $line; done
for f in *.txt; do echo $f; done
while read line ; do echo $line; done < a.txt
cat a.txt | while read line; do echo $line; done
</div>
9. 删除空行
cat a.txt | sed -e '/^$/d'
(echo "abc"; echo ""; echo "ddd";) | awk '{if (0 != NF) print $0;}'
</div>
10. 比较文件的修改时间
[[ file1.txt -nt file2.txt ]] && echo true || echo false
[[ file1.txt -ot file2.txt ]] && echo true || echo false
</div>
11. 实现Dictionary结构
eval "hkey_$1"="$2"
}
hget() {
eval echo '${'"hkey_$1"'}'
}
$ hput k1 aaa
$ hget k1
aaa</div>
12. 去掉第二列
$echo 'a b c d e f' | cut -d ' ' -f1,3-
$a c d e f
</div>
13. 把stderr输出保存到变量
$ a=$( (echo 'out'; echo 'error' 1>&2) 2>&1 1>/dev/null)
$ echo $a
error</div>
14. 删除前3行
$cat a.txt | sed 1,3d
</div>
15. 读取多个域到变量
read a b c <<< "xxx yyy zzz"
</div>
16. 遍历数组
for i in ${array[@]}
do
echo $i
done</div>
17. 查看目录大小

