1 shell 调试
sh -x somefile.sh
在somefile.sh 文件里加上set+x set-x
2 用 && || 简化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"
3 判断文件非空
if [[ -s $file ]]; then
echo "not empty"
fi
4 获取文件大小
stat -c %s $file
stat --printf='%s\n' $file
wc -c $file
5 字符串替换
${string//pattern/replacement}
a='a,b,c'
echo ${a//,/ /}
6 Contains 子字符串?
string="My string"
if [[ $string == *My* ]]; then
echo "It's there!"
fi
7 rsync备份
rsync -r -t -v /source_folder /destination_folder
rsync -r -t -v /source_folder [user@host:/destination_folder
8 批量重命名文件
为所有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/' {
} \;
9 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
10 删除空行
cat a.txt | sed -e '/^$/d'
(echo "abc"; echo ""; echo "ddd";) | awk '{if (0 != NF) print $0;}'
11 比较文件的修改时间
[[ file1.txt -nt file2.txt ]]