bash check if user mount fails
Asked Answered
B

3

5

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?

Bespoke answered 18/5, 2009 at 23:48 Comment(0)
D
6

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

Degeneracy answered 18/5, 2009 at 23:53 Comment(2)
I would point out that this is how you check the success of pretty much any well behaved application on most platforms.Protease
Thanks for your help. I'm still getting my bearings when it comes to bash.Bespoke
F
3

I was trying to check if a directory was not a mountpoint for an sshfs mount. Using the example from above failed:

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

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
Fredi answered 10/5, 2013 at 20:45 Comment(0)
S
0

Tested this on oracle linux 8 and works

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

This code worked on Centos 7

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

Spheroid answered 17/5 at 17:21 Comment(2)
This does not provide an answer to the question. Once you have sufficient reputation you will be able to comment on any post; instead, provide answers that don't require clarification from the asker. - From ReviewOuachita
please use code highlightersMelodymeloid

© 2022 - 2024 — McMap. All rights reserved.