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?
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).
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
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
© 2022 - 2024 — McMap. All rights reserved.