代码之家  ›  专栏  ›  技术社区  ›  Stephan

bash检查用户安装是否失败

  •  3
  • Stephan  · 技术社区  · 15 年前

    我正在写一个脚本,通过sftp传输一些文件。我希望通过使用sshfs挂载目录作为本地传输来进行传输,因为这样可以更容易地创建所需的目录结构。我的问题是我不确定如何处理没有网络连接的情况。基本上,我需要一种方法来判断sshfs命令是否失败。如果无法装载远程目录,有什么办法可以使脚本退出吗?

    2 回复  |  直到 11 年前
        1
  •  5
  •   Community CDub    7 年前

    只是测试一下 sshfs 返回0(成功):

    sshfs user@host:dir mountpoint || exit 1
    

    上面的工作是因为在bash中 || 表演 short-circuit evaluation . 允许您打印错误消息的更好解决方案如下:

    if !( sshfs user@host:dir mountpoint ); then
      echo "Mounting failed!"
      exit 1
    fi
    

    编辑:

    我会指出,这就是在大多数平台上检查几乎所有行为良好的应用程序成功的方法。艾斯 Sparr 1分钟前

    的确。更详细地说:大多数应用程序在成功时返回0,在失败时返回另一个值。shell知道这一点,因此将返回值0解释为true,任何其他值解释为false。因此,逻辑或和否定测试(使用感叹号)。

        2
  •  2
  •   user1690442    11 年前

    我试图检查目录是否不是 sshfs 安装。使用上面的示例失败:

    if !( mountpoint -q /my/dir ); then
        echo "/my/dir is not a mountpoint"
    else
        echo "/my/dir is a mountpoint"
    fi
    

    错误: -bash: !( mountpoint -q /my/dir ): No such file or directory

    我修改了我的代码,并取得了成功:

    if (! mountpoint -q /my/dir ); then
        echo "/my/dir is not a mountpoint"
    else
        echo "/my/dir is a mountpoint"
    fi
    
    推荐文章