标签 shell 下的文章

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快一点。

CPU满载运行命令

这是一个简单的方法。

命令有三种:

  1. sha1sum /dev/zero
  2. md5sum /dev/zero
  3. dd if=/dev/zero of=/dev/null

这三种命令都是单核心,2个核心就运行2个进程,如:

md5sum /dev/zero | md5sum /dev/zero

结束按Ctrl+C

后台运行:

md5sum /dev/zero | md5sum /dev/zero &

结束运行killall md5sum