1

I need to test whether /etc/mtab is a symbolic link to /proc/something. I need to comply with the POSIX standard. (In general should run on RHEL 5 to RHEL 7.)  This is what I have so far:

#!/bin/bash
if [ $(readlink -f /etc/mtab | grep '\/proc\/') ]; then
    echo do something related to proc
else
    echo do something other than proc
fi

Am I missing some edge cases?

3
  1. What if /etc/mtab is a symbolic link to /home/mikasa/proc/something?  You should probably add a ^ to your grep regular expression.
  2. Speaking of which, / is not a special character in regular expressions, so you don’t need to escape them.
  3. You should quote shell variable references unless you have a good reason not to, and you’re sure you know what you’re doing.  This includes $(…) command substitutions.  In the truly pathological edge case where /etc/mtab is a symbolic link to /proc/foo = bar, your command expands to
    if [ /proc/foo = bar ]
    which, of course, evaluates to false.  You can fix this by putting the $(…) into double quotes:
    if [ "$(readlink -f /etc/mtab | grep '^/proc/')" ]; then
  4. But you don’t need to do command substitution or test (a.k.a. []).  grep gives an exit status that indicates whether it found the pattern you told it to look for, so you should be able to simplify your command to:
    if readlink -f /etc/mtab | grep '^/proc/' > /dev/null; then
2

Your code seems to do what you want though readlink -f is not POSIX.

Another nice non-POSIX solution would be:

if [ "$(df --output=fstype  /etc/mtab  | tail -n +2)" = "proc" ]; then

(This should even work if the proc filesystem is not mounted on /proc)

But maybe in the real world it could be enough to simply check

if [ -L /etc/mtab ]; then

The last one is even used in util-linux test-suite and they got no bug reports so far. Seems like on any existing Linux distros /etc/mtab is either a regular file or a symlink to /proc/self/mounts.

  • Some of the experimental system do have a symbolic link to something which is not proc so could not rely on the last test. – MikasaAckerman Oct 5 '16 at 18:12
  • OK then go with one of the GNUisms or see tlrobinson's answer here stackoverflow.com/questions/7665/… – rudimeier Oct 5 '16 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.