1

I'm creating a script which check if a VPS do have TUN driver enabled. The check command is :

cat /dev/net/tun

if it return:

cat: /dev/net/tun: File descriptor in bad state

the module is enabled. otherwise return ERROR.

Here is my script:

tunstring="File descriptor in bad state"
if cat /dev/net/tun | grep -q "$tunstring"; then
    echo "GOOOOOD"
else
    echo "ERROR"
fi

I get ERROR message.

I tried the same script with a text file and it worked...

fredtantini
  • 15,966
  • 8
  • 49
  • 55
Rck
  • 33
  • 5
  • 1
    You could skip the grep entirely and just look at the exit status of `cat`: `if cat /dev/net/tun; then echo ERROR; else echo GOOOOD; fi` – Charles Duffy Jan 08 '15 at 15:58
  • ...I'd also consider looking for the driver more directly -- `lsmod | grep tun`, for instance -- rather than relying on behavior it doesn't document / guarantee to retain for future versions. (Who's to say that `cat /dev/net/tun` will continue to work? Future versions may _always_ fail attempts to read without breaking other programs that use it, since that node is used for `ioctl()` calls, not conventional read/write IO). – Charles Duffy Jan 08 '15 at 16:00

1 Answers1

3

Since that output is being written on stderr you can use:

tunstring="File descriptor in bad state"
if cat /dev/net/tun |& grep -q "$tunstring"; then
    echo "GOOOOOD"
else
    echo "ERROR"
fi

|& pipes previous command's stdout and stderr to next in pipe line.

Looks like your VPS path i.e /dev/net/tun isn't valid anymore and cat command is failing to read it.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • Some information on why `cat` is outputting to standard error would be useful – Tom Fenech Jan 08 '15 at 15:47
  • Yes I added but I can only guess why `/dev/net/tun` isn't valid VPS – anubhava Jan 08 '15 at 15:50
  • 1
    Your code does solve the problem as it is defined (so +1), but maybe the OP is trying to solve the wrong problem... See here: https://vpsboard.com/topic/175-bash-script-to-check-if-tuntap-is-enabled-and-if-so-do-stuff/ – poncha Jan 08 '15 at 15:53