bash 检查用户挂载是否失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/880330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash check if user mount fails
提问by Stephan
I'm writing a script to transfer some files over sftp. I wanted do the transfer as a local transfer by mounting the directory with sshfs because it makes creating the required directory structure much easier. The problem I'm having is I'm unsure how to deal with the situation of not having a network connection. Basically I need a way to tell whether or not the sshfs command failed. Any ideas how to cause the script to bail if the remote directory can't be mounted?
我正在编写一个脚本来通过 sftp 传输一些文件。我想通过使用 sshfs 挂载目录来将传输作为本地传输进行,因为它使创建所需的目录结构变得更加容易。我遇到的问题是我不确定如何处理没有网络连接的情况。基本上我需要一种方法来判断 sshfs 命令是否失败。如果无法挂载远程目录,如何使脚本保释的任何想法?
回答by Stephan202
Just test whether sshfsreturns 0 (success):
只需测试是否sshfs返回 0(成功):
sshfs user@host:dir mountpoint || exit 1
The above works because in bash the logical-or ||performs short-circuit evaluation. A nicer solution which allows you to print an error message is the following:
上述工作是因为在 bash 中逻辑或||执行短路评估。允许您打印错误消息的更好的解决方案如下:
if !( sshfs user@host:dir mountpoint ); then
echo "Mounting failed!"
exit 1
fi
Edit:
编辑:
I would point out that this is how you check the success of pretty much any well behaved application on most platforms. – Sparr1 min ago
我要指出的是,这就是您在大多数平台上检查几乎所有表现良好的应用程序是否成功的方式。–斯帕尔1 分钟前
Indeed. To elaborate a bit more: most applications return 0 on success, and another value on failure. The shell knows this, and thus interprets a return value of 0 as true and any other value as false. Hence the logical-or and the negative test (using the exclamation mark).
的确。详细说明一下:大多数应用程序在成功时返回 0,在失败时返回另一个值。shell 知道这一点,因此将返回值 0 解释为 true,将任何其他值解释为 false。因此,逻辑或和否定测试(使用感叹号)。
回答by Stephan
I was trying to check if a directory was not a mountpoint for an sshfsmount. Using the example from above failed:
我试图检查目录是否不是挂载的sshfs挂载点。使用上面的例子失败:
if !( mountpoint -q /my/dir ); then
echo "/my/dir is not a mountpoint"
else
echo "/my/dir is a mountpoint"
fi
The error: -bash: !( mountpoint -q /my/dir ): No such file or directory
错误: -bash: !( mountpoint -q /my/dir ): No such file or directory
I amended my code with the following and had success:
我用以下内容修改了我的代码并取得了成功:
if (! mountpoint -q /my/dir ); then
echo "/my/dir is not a mountpoint"
else
echo "/my/dir is a mountpoint"
fi

