IF statement problem

Well, I know this must be a trivial problem but it’s got me stumped!

As part of a mini project I want to detect whether or not a USB stick is inserted. Part of the script is as follows:
With USB stick inserted:

keith@T500:~/.bin$ df
Filesystem 1K-blocks Used Available Use% Mounted on
udev 966912 0 966912 0% /dev
tmpfs 197460 6484 190976 4% /run
……. lots of lines………
mpfs 197460 68 197392 1% /run/user/1000
/dev/sdb1 30286416 4064832 26221584 14% /media/keith/AUDIO

keith@T500:~/.bin$ if [ -d /media ]; then echo media present; fi
media present
keith@T500:~/.bin$

then remove USB stick:

keith@T500:~/.bin$ umount /dev/sdb1
keith@T500:~/.bin$ df
Filesystem 1K-blocks Used Available Use% Mounted on
udev 966912 0 966912 0% /dev
tmpfs 197460 6484 190976 4% /run
……. lots of lines………
mpfs 197460 68 197392 1% /run/user/1000
…………no /media shown……………

keith@T500:~/.bin$ if [ -d /media ]; then echo media present; fi
media present
keith@T500:~/.bin$ if [ ! -d /media ]; then echo media present; fi
keith@T500:~/.bin$

The IF statement appears to be working the wrong way round. What am I doing incorrectly? It’s driving me mad!
Advice would be welcome.

What that says is - if /media exists and is a directory (-d), then echo “media present” to standard out, then finish.

The problem is /media ALWAYS exists, and is ALWAYS a directory.

See here for what “if” options mean
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html


What you want is something more like:

if [ -d /media/$USER/* ]; then echo "media present"; fi

or:

if [ -d /media/$USER/* ]; then echo "media present"; else echo "media not present"; fi

Oh - of course!!! In fact I have used that trick in another context but didn’t realise I had cracked it.
Thank you for your explanation about /media being always there - obvious now you mention it, but then I always was a bit slow.

Thank you, Mark, as always.
Keith

Ah, but try this:

keith@T500:~/.bin$ fileref=“qw”
keith@T500:~/.bin$ echo $fileref
qw
keith@T500:~/.bin$ if [ $fileref=“qw” ]; then echo “qw”; fi
qw
keith@T500:~/.bin$ if [ ! $fileref=“qw” ]; then echo “qw”; fi
keith@T500:~/.bin$ (so far OK)
keith@T500:~/.bin$ if [ $fileref=“QW” ]; then echo “QW”; fi
QW
keith@T500:~/.bin$ if [ ! $fileref=“QW” ]; then echo “QW”; fi
keith@T500:~/.bin$

The last two statements give wrong answers as $fileref=“qw” as shown earlier.
A slightly different problem, I grant you, but relevant. Can you help me with this one?

Add some spaces around the “=” … as in

fileref="qw"
if [ $fileref = "qw" ]; then echo "qw"; fi
if [ $fileref = "QW" ]; then echo "QW"; fi

It must be really nice to know what you are doing!
I thought I had tried every combination of spaces and non-spaces, which requirement changes from command to command.

Thank you Mark.

I never claimed to know what I’m doing … seriously, that’d be a HUGE mistake :wink: