shell 中的常用技巧
本文收集了一堆的shell脚本技巧,主要方便自己查阅,技巧出自脚本之家中的博客,自己也增加了实现目的的其他方法,方便以后自己查阅:0. shell 调试
代码如下:
sh -x somefile.sh 在somefile.sh 文件里加上set+x set-x
1. 用 && || 简化if else
代码如下:
gzip -t a.tar.gz
if [[ 0 == $? ]]; then
echo "good zip"
else
echo "bad zip"
fi
可以简化为:
复制代码代码如下:
gzip-t a.tar.gz && echo "good zip" || echo "bad zip" 2. 判断文件非空
代码如下:
if [[ -s $file ]]; then
echo "not empty"
fi
3. 获取文件大小
代码如下:
stat -c %s $file
stat --printf='%s\n' $file
wc -c $file
4. 字符串替换
代码如下:
${string//pattern/replacement}
a='a,b,c'
echo ${a//,/ /}
5. Contains 子字符串?
string="My string"
if [[ $string == *My* ]]; then
echo "It's there!"
fi
6. rsync备份
代码如下:
rsync -r -t -v /source_folder /destination_folder
rsync -r -t -v /source_folder [user@host:/destination_folder
7. 批量重命名文件
为所有txt文件加上.bak 后缀:
代码如下:
rename '.txt' '.txt.bak' *.txt 去掉所有的bak后缀:
代码如下:
rename '*.bak' '' *.bak 把所有的空格改成下划线:
代码如下:
find path -type f -exec rename 's/ /_/g' {} \; 把文件名都改成大写:
代码如下:
find path -type f -exec rename 'y/a-z/A-Z/' {} \; 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
9. 删除空行
代码如下:
cat a.txt | sed -e '/^$/d'
(echo "abc"; echo ""; echo "ddd";) | awk '{if (0 != NF) print $0;}'
10. 比较文件的修改时间
代码如下:
[[ file1.txt -nt file2.txt ]] && echo true || echo false
[[ file1.txt -ot file2.txt ]] && echo true || echo false
11. 实现Dictionary结构
代码如下:
hput() {
eval "hkey_$1"="$2"
}
hget() {
eval echo '${'"hkey_$1"'}'
}
$ hput k1 aaa
$ hget k1
aaa
12. 去掉第二列
代码如下:
$echo 'a b c d e f' | cut -d ' ' -f1,3-
$a c d e f
13. 把stderr输出保存到变量
代码如下:
$ a=$( (echo 'out'; echo 'error' 1>&2) 2>&1 1>/dev/null)
$ echo $a
error
14. 删除前3行
代码如下:
$cat a.txt | sed 1,3d 15. 读取多个域到变量
代码如下:
read a b c
页:
[1]