shell 脚本记录

本文详细介绍了49个实用的Shell脚本技巧,包括shell调试、文件操作、字符串处理、循环控制、流程控制、数组操作、正则表达式等,旨在帮助开发者提升Shell脚本编写能力。
摘要由CSDN通过智能技术生成

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 ]]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值