标签 shell 下的文章

自定义启动 rsync 守护

OpenWRT 上面挂了一个 2T 硬盘用来异地备份群晖,需要开启 rsync 守护。
OP 自带的 rsync 配置文件是 /etc/rsyncd.conf,我需要用自己的配置
于是需要先关闭系统自带的 rsync 进程,我脚本如下:

#!/bin/sh
killall rsync
rsync --daemon --config=/mnt/sda3/my.files/rsync/rsyncd.conf

我把这个脚本放进 OP 开机启动项,rsync 进程倒是结束了,但是新的 rsync 进程并没有成功,于是我手动运行它,提示:

failed to lock pid file /var/run/rsyncd.pid: Resource temporarily unavailable

再添加一个 sleep 1

#!/bin/sh
killall rsync
sleep 1
rsync --daemon --config=/mnt/sda3/my.files/rsync/rsyncd.conf

就可以了。

shell多条件逻辑判断

用括号分隔,例子:

#!/bin/bash

a=asdf
b=23rr
c=23fsd
d=j32l4
e=j123
f=123

# a=asdf b=23r2r c=23fsdf e=j123 or j456
# or
# d=j32l4 f=123

if ([ $a = 3434sdf ] && [ $b = 23rr ] && [ $c = 23fsd ] && ([ $e = j123 ] || [ $e = j456 ])) || ([ $d = j32l4 ] && [ $f = 123 ])

then
   echo "执行"
else
   echo "不执行"
fi

shell 自动计算 bytes KB MB

自动计算 bytes 为 KB、MB、GB、TB,代码分2种,一种显示整数,一种显示2位小数。

#!/bin/sh
human_bytes(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} Bytes && break
  KB=$(((B+512)/1024))
  [ $KB -lt 1024 ] && echo ${KB} KiB && break
  MB=$(((KB+512)/1024))
  [ $MB -lt 1024 ] && echo ${MB} MiB && break
  GB=$(((MB+512)/1024))
  [ $GB -lt 1024 ] && echo ${GB} GiB && break
  echo $(((GB+512)/1024)) TiB
done
}

human_bytes_2(){
while read B dummy; do
  [ $B -lt 1024 ] && echo ${B} Bytes && break
  KB=$(echo "scale = 2; $B/1024" | bc | awk '{printf "%.2f", $0}')
  [ $(echo "$KB > 1024" | bc) -eq 0 ] && echo ${KB} KiB && break
  
  MB=$(echo "scale = 2; $KB/1024" | bc | awk '{printf "%.2f", $0}')
  [ $(echo "$MB > 1024" | bc) -eq 0 ] && echo ${MB} MiB && break
  
  GB=$(echo "scale = 2; $MB/1024" | bc | awk '{printf "%.2f", $0}')
  [ $(echo "$GB > 1024" | bc) -eq 0 ] && echo ${GB} GiB && break
  
  echo $(echo "scale = 2; $GB/1024" | bc | awk '{printf "%.2f", $0}') TiB
done
}

dd命令清除磁盘数据

1.先查看扇区数量和大小

root@ds3617xs:~# fdisk -l /dev/sda
Disk /dev/sda: 10 GiB, 10737418240 bytes, 20971520 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

2.用DD写入数据0或随机值

root@ds3617xs:~# dd if=/dev/urandom of=/dev/sda bs=512 count=20971520
20971520+0 records in
20971520+0 records out
10737418240 bytes (11 GB) copied, 1793.47 s, 6.0 MB/s
root@ds3617xs:~#

/dev/urandom随机很慢,/dev/zero快一点。