开发者

Execute command in bash with parameter and return value

I have the following script开发者_C百科 to check if a NFS mount is currently mounted on the server :

#!/bin/bash
$targetserver=192.168.3.1
commandline="mount | grep '$targetserver' | wc -l"
checkmount=`$commandline`

if [ $checkmount == "1" ]; then
  echo "Mounted !"
else
  echo "Not mounted"
fi

But it seems that my checkmount is not returning anything.

What am I missing here ?


This should work better.

#!/bin/bash
targetserver="192.168.3.1"
commandline=$(mount | grep "$targetserver" | wc -l)

if [ $commandline -gt 0 ]; then
  echo "Mounted !"
else
  echo "Not mounted"
fi

You could shorten it down though, using $?, redirection and control operators.

targetserver="192.168.3.1"
mount | grep "$targetserver" > /dev/null && echo "mounted" || echo "not mounted"

Depending on system grep /etc/mtab directly might be a good idea too. Not having to execute mount would be cleaner imho.

Cheers!


I'd maybe do this, or just but the content of the function directly in if, if you just use it in one place.

nfsismounted() {
mount | grep -qm1 "$1":
}

q = quiet (we just want the return code), m1 = quit on first match.

And use it as such:

if nfsismounted 192.168.0.40; then
    echo "Mounts found"
else
    echo "Not mounts"
fi

A side note on the code in your question, you don't test with == in the shell, just =. == Will break on, for example, dash which is /bin/sh in Debian/Ubuntu since a while.

Edit: For added portability (non-GNU grep), remove the flags on grep and > /dev/null. Tests were done on bash/dash/ksh

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜