我读到,按名称(/dev/sdxy)安装设备是不安全的,因为设备的名称在重新启动之间可能会发生变化。因此,我想用UUID来代替设备名生成一个fstab文件。互联网上的教程建议我找到我想要的设备的UUID,并手动复制-粘贴到/etc/fstab中。
我认为必须有一种方法来实现自动化,我正在尝试从脚本中获得sed。下面是我最接近于工作脚本的部分:
#!/bin/bash
function GetUUID()
{
# Arg 1 is expected to be a device (such as /dev/sdc1)
# This function calls blkid on the device and prints to stdout UUID=[uuid], without quotes, so that it can be passed out to SED.
echo -n calling GetUUID on $1
FullString=$(blkid $1 | tr -d '"')
UUID=$(echo ${FullString} | cut -d ' ' -f2)
echo $UUID
}
# Greps /etc/mtab and looks for user given disk (say, /dev/sdc)
# Changes the names of all mounted partitions of that disk (eg all /dev/sdcx) to their UUIDs, in compatible format with /etc/fstab
# Outputs results to stdout
if [[ $# -eq 0 ]]
then
# If no argument, I will not try to guess a default, that looks dangerous.
echo "Usage : RobustMtabCopy /dev/somedisk (will search mstab for all /dev/somediskX and replace the names by their UUIDS)"
exit 22
else
# Else, look for anything like /dev/somediskX, source the function that will make the output pretty, get the pretty form of UUID, and put it in place of the device name in the output.
grep $1 /etc/mtab | sed -E "s|(${1}[[:digit:]])|$(GetUUID \1)|g"
fi预期的输出如下所示:
UUID=SOME-UUID mount-point fs options 0 0
UUID=SOME-OTHER-UUID mount-point fs options 0 0实际产出:
./script.sh /dev/sdc
mount-point fs options 0 0
mount-point fs options 0 0一些调试表明,我使用参数"1“调用GetUUID (因此blkid输出空字符串)。逃避这一切没有任何帮助。
有几个很好的建议不太符合我的要求:
任何帮助都将不胜感激。
发布于 2022-04-15 14:49:18
将GNU用于替换命令的e修饰符:
grep "$1" /etc/mtab |
sed -E 's|(.*)('"$1"')(.*)|printf "UUID=%s %s%s\\n" "$(blkid -s UUID -o value "\2")" "\1" "\3"|e'但是要小心:您必须传递一个与完整设备名称完全匹配的正则表达式,而不是更多。示例:
$ ./script.sh '/dev/sdc[0-9]*'
UUID=4071fbd0-711a-477d-877a-ee4b6be261fc /tmp ext4 rw,relatime 0 0
UUID=a34227b0-bb5e-44fb-9207-dc48cf4be022 /home ext4 rw,relatime 0 0
UUID=bcfa9073-79ad-43ca-ba34-ceb8aecb23bf /var ext4 rw,relatime 0 0如果像在您的示例中一样,您已经知道了您拥有的设备类型(/dev/sd[a-z][0-9]+),并且只想传递您可以修改的sed脚本的主要部分:
grep "$1" /etc/mtab |
sed -E 's|(.*)('"$1"'\S+)(.*)|printf "UUID=%s %s%s\\n" "$(blkid -s UUID -o value "\2")" "\1" "\3"|e'然后:
$ ./script.sh '/dev/sdc'
UUID=4071fbd0-711a-477d-877a-ee4b6be261fc /tmp ext4 rw,relatime 0 0
UUID=a34227b0-bb5e-44fb-9207-dc48cf4be022 /home ext4 rw,relatime 0 0
UUID=bcfa9073-79ad-43ca-ba34-ceb8aecb23bf /var ext4 rw,relatime 0 0https://stackoverflow.com/questions/71884563
复制相似问题