Using Echo Output For New Condidition


Recommended Posts

I want to use this function in my bash script

check-nfs ()
{
echo "checking"
mount | grep 192.168.1 > /dev/null
if [ "$?" = 0 ]
then
  echo "NFS is mounted"
else
  echo "NFS is not mounted"
fi
}

depending on the output either "NFS is mounted" or "NFS is not mounted" how could i use that output as a condition in an other if else statement? Sorry if this is not clear.

Link to post
Share on other sites

You can pipe the function as you would any utility, but if you only want to know whether NFS is mounted and don't care about the output of the function it might be easier to use 'return'. 'return' will cause the function to immediately return to its caller with a specifiable exit status; as usual $? can be used to access the exit status. For example

check-nfs ()
{
   echo "checking"
   mount | grep 192.168.1 > /dev/null
   if [ "$?" = 0 ]
   then
       echo "NFS is mounted"
       return 0
   else
       echo "NFS is not mounted"
       return 1
   fi
}

which could be used like so

check-nfs
if [ "$?" = 0 ]
then
   # do something with NFS
else
   # mount NFS or panic
fi

Edited by jcl
Link to post
Share on other sites

return was what I was looking for, Thanks :-) I originally tried to use some other ways that did not work. I will give you guys something to chuckle at

here are some failed attemps:

check-nfs ()
{
echo "checking"
mount | grep 192.168.1 > /dev/null
if [ "$?" = 0 ]
then
  echo "NFS is mounted"
  exit 0 #this gave me the correct return, but had the negative effect of stoping my script
else
  echo "NFS is not mounted"
  exit 1
fi
}

I also tried this, I was just reaching for anything that might work ;-)

check-nfs ()
{
echo "checking"
mount | grep 192.168.1 > /dev/null
if [ "$?" = 0 ]
then
  echo "NFS is mounted"
  $?=0
else
  echo "NFS is not mounted"
  $?=1
fi
}

Link to post
Share on other sites

exit was the first thing I considered too :)

The second one was a good idea; too bad the shell is a bit inconsistent about how it handles variables. Many rather useful variables are untouchable, often because of syntax issues.

Edited by jcl
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...