Search code examples
bashsshfs

bash check if user mount fails


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?


Solution

  • Just test whether sshfs returns 0 (success):

    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:

    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. – Sparr 1 min ago

    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).