![如何查找 fstab 文件中的冲突](https://linux22.com/image/125113/%E5%A6%82%E4%BD%95%E6%9F%A5%E6%89%BE%20fstab%20%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84%E5%86%B2%E7%AA%81.png)
有时我们注意到 /etc/fstab 文件中存在冲突,如下例所示
/dev/sdg 出现两次!
/data/sdb 出现两次!
#
# /etc/fstab
# Created by anaconda on Wed Nov 9 13:26:03 2016
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/vg00-OS-linux_root / xfs defaults
0 0
UUID=cc749f07-ad72-49e8-ab19-ec6532f5e9 /boot xfs
defaults 0 0
/dev/mapper/vg00-OS-linux_var /var xfs defaults
0 0
/dev/mapper/vg00-OS-linux_swap swap swap defaults
0 0
/dev/sdc /data/sdc ext4 defaults,noatime 0 0
/dev/sdb /data/sdb ext4 defaults,noatime 0 0
/dev/sde /data/sde ext4 defaults,noatime 0 0
/dev/sdf /data/sdf ext4 defaults,noatime 0 0
/dev/sdd /data/sdd ext4 defaults,noatime 0 0
/dev/sdg /data/sdb ext4 defaults,noatime 0 0
/dev/sdg /data/sdg ext4 defaults,noatime 0 0
/dev/sdh /data/sdh ext4 defaults,noatime 0 0
/dev/sdi /data/sdi ext4 defaults,noatime 0 0
/dev/sdj /data/sdj ext4 defaults,noatime 0 0
/dev/sdk /data/sdk ext4 defaults,noatime 0 0
/dev/sdl /data/sdl ext4 defaults,noatime 0 0
我们想要创建简单的验证来查找 fstab 文件中第一个字段或第二个字段的冲突
为此目的最好的语法是什么?
验证应在第一个字段或第二个字段中找到重复的单词,(语法行应尽可能短)
预期产出 -失败/正常
&(如果失败,应该打印第一个字段/第二个字段中的所有重复单词)
答案1
awk ' !/^#/ { if (seendev[$1]++) { print; ++rc; } if (seenmnt[$2]++) { print; ++rc; } }
END { exit rc }' < /etc/fstab
上面的 awk 单行代码将打印与第 1 列(设备)或第 2 列(安装点)重复的任何行,并且如果发生上述情况,还将以非零返回代码退出。
答案2
#!/bin/sh
# Filter out comments and blank lines from /etc/fstab, pick 1st/2nd field,
# then sort and find duplicates.
DUP_DEVS="$(grep -v -e '^#' -e '^$' /etc/fstab | awk '{ print $1;}' | sort | uniq -d)"
DUP_MOUNTS="$(grep -v -e '^#' -e '^$' /etc/fstab | awk '{ print $2;}' | sort | uniq -d)"
if [ -z "$DUP_DEVS" ] && [ -z "$DUP_MOUNTS" ]; then
echo "ok"
exit 0
else
echo "fail"
if [ ! -z "$DUP_DEVS" ]; then
echo "Duplicate devices:"
echo "$DUP_DEVS"
else
echo "Duplicate mount points:"
echo "$DUP_MOUNTS"
fi
exit 1
fi
答案3
完整的解决方案awk
:
awk '/^\/dev\//{
if (devs[$1]++) dups[$1];
if (data[$2]++) dups[$2]
}
END{
res="Ok";
for (d in dups) { res="Fail\nDuplicates: "; break }
print "Result: "res;
for (d in dups) print d
}' /etc/fstab
输出:
Result: Fail
Duplicates:
/dev/sdg
/data/sdb