Search code examples
linuxbashif-statementredhat

Trying to use the output of Grep -E in if statement in bash script


I am trying to use the output of $mount to check whether there are network mount points and if so, do what is stated. Instead, I keep getting the else statement no matter what I try.

If I run mount | egrep 'cifs|nfs|rpc' on command line, I see that there are network mounts. How do I do this in a script? I CANNOT figure it out after much trial and error and want to pull my hair out.

Red Hat 6.8 is my OS but will need it to work for 6.x and 7.x

Sample output when run at command line:

~# mount | egrep 'cifs|nfs|rpc' 

sunrpc on /var/lib/nfs/rpc_pipefs type rpc_pipefs (rw)
machine.example.com:/export/home/x/ICD103 on
/mnt/ICD103 type nfs(rw,soft,int,rsize=8192,wsize=8192,sloppy,vers=4,addr=xx.xxx.xxx.xx,clientaddr=10.xxx.xxx.xxx)
//new-devstore/Stable/Assets on /mnt/assets type cifs (rw)
mount=$(mount | egrep 'cifs|nfs|rpc')

if $mount; then
    mount > $destBAK/mount.txt;
    cp -p /etc/auto.cifs > $destBAK 2>/dev/null;
    cp -p /etc/auto.master > $destBAK 2>/dev/null;
    cp -p /root/.smbauth > $destBAK 2>/dev/null;
    cp -p /etc/fstab > $destBAK 2>/dev/null;
else
    echo "No Network Mount"
fi

Output after running ./backup.sh

~# ./backup.sh
Making backup directory /tmp/BAK_2017-10-13 now 
Copying files to /tmp/BAK_2017-10-13
./backup.sh: line 34: sunrpc: command not found
No Network Mount

Solution

  • Saying

    if $mount
    

    will try to execute the value of $mount. It's basically like saying

    if "foo"; then echo ok; else echo no; fi
    

    Unless your string has a successfully executable value, it will always throw an error and give you the else.

    Why assigning to a var?

    if mount | egrep 'cifs|nfs|rpc'
    then ...
    

    will use the return from the egrep.

    If you do need to catch and save the output collectively, then use

    if [[ -n "$mount" ]] # tests string for nonzero length
    then ...
    

    If you need the output lines individually, try

    hit=0
    mount | egrep 'cifs|nfs|rpc' |
      while read mnt
      do hit=1
         # ... all your mount code above
      done
    if (( hit )) # math evaluation
    then : any remaining stuff you might need to do
    else echo "No Network Mount"
    fi
    

    update --

    an attempt to re-engineer what you want:

    tmp=/tmp/mount.txt
    mount > $tmp
    if egrep -q 'cifs|nfs|rpc' $tmp
    then mv $tmp $destBAK
         cp -p /etc/auto.cifs $destBAK
         cp -p /etc/auto.master $destBAK
         cp -p /root/.smbauth $destBAK
         cp -p /etc/fstab $destBAK
    else
        echo "No Network Mount"
        rm $tmp
    fi
    

    This should work. I took off all the stderr redirections because you should know about errors, and ideally handle them, but at least here it will report them.

    This doesn't work for you?