Bash 脚本 - 卸载设备,但如果未安装也不会失败?
我正在编写一个 bash 脚本,并且设置了 errexit,这样如果任何命令不返回 0 退出代码(即如果任何命令未成功完成),脚本就会终止。这是为了确保我的 bash 脚本是健壮的。
我必须安装一些文件系统,复制一些文件,然后卸载它。我在开头放置了一个umount /mnt/temp
,这样它就会在执行任何操作之前卸载它。但是,如果未安装,则 umount 将失败并停止我的脚本。
是否可以执行umount --dont-fail-if-not-mounted /mnt/temp
?那么如果设备未安装它会返回0?就像 rm -f 一样?
I'm writing a bash script and I have errexit
set, so that the script will die if any command doesn't return a 0 exit code, i.e. if any command doesn't complete successfully. This is to make sure that my bash script is robust.
I have to mount some filesystems, copy some files over, the umount it. I'm putting a umount /mnt/temp
at the start so that it'll umount it before doing anything. However if it's not mounted then umount will fail and stop my script.
Is it possible to do a umount --dont-fail-if-not-mounted /mnt/temp
? So that it will return 0 if the device isn't mounted? Like rm -f
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
忽略返回代码的标准技巧是将命令包装在始终评估为成功的布尔表达式中:
The standard trick to ignore the return code is to wrap the command in a boolean expression that always evaluates to success:
忽略退出代码并不真正安全,因为它无法区分已卸载的资源和卸载已安装资源的失败。
我建议测试该路径是否使用
mountpoint
挂载,当且仅当给定路径是已挂载的资源时,它返回 0。如果未安装给定路径,此脚本将以 0 退出,否则它将给出 umount 的退出代码。
您也可以将其作为单行进行。
Ignoring exit codes isn't really safe as it won't distinguish between something that is already unmounted and a failure to unmount a mounted resource.
I'd recommend testing that the path is mounted with
mountpoint
which returns 0 if and only if the given path is a mounted resource.This script will exit with 0 if the given path was not mounted otherwise it give the exit code from
umount
.You an also do it as a one liner.
假设你的
umount
在设备未挂载时返回1,你可以这样做:那么如果
umount
返回0或1(即卸载成功),bash将假设没有错误或设备未安装),但如果返回任何其他代码(例如您没有卸载设备的权限),则会停止脚本。Assuming that your
umount
returns 1 when device isn't mounted, you can do it like that:Then bash will assume no error if
umount
returns 0 or 1 (i.e. unmounts successfully or device isn't mounted) but will stop the script if any other code is returned (e.g. you have no permissions to unmount the device).我只是发现“:”更有用,并且想要一个类似的解决方案,但让脚本知道发生了什么。
尽管 umount 失败,但该消息返回 true。
I just found the ":" more use ful and wanted a similar solution but let the script know whats happening.
This returns true with the message, though the umount failed.