0

What does '[' ']' indicate in this output?

$ bash -ex ~/bin/client_services 
+ : starting daemons reqd. for clients
++ ps aux
++ grep -q memcached
+ '[' ']'

My source file is:

if [ `ps aux | grep -q memcached` ]; then
  echo 'Memcached exists'
fi
american-ninja-warrior
  • 7,397
  • 11
  • 46
  • 80
  • 1
    It means your command substitution didn't have any output. – Charles Duffy Aug 10 '18 at 16:15
  • 1
    Change the code to just `if ps aux | grep -q memcached; then` to directly test the exit status of your `grep` command, without using `[` to try to (buggily, in this case, due to bad quoting) evaluate its stdout first. – Charles Duffy Aug 10 '18 at 16:16
  • 1
    ...or, if you **really** want to collect the output and test whether it's empty, add quotes: `if [ "$(ps aux | grep memcached)" ]` -- note that there's no `-q`. This is slower, though, and has more moving parts. – Charles Duffy Aug 10 '18 at 16:17
  • ...that said, generally speaking, testing the output of `ps` is a code smell -- it means you aren't using your operating system's process supervision tools to manage daemons in a more robust way. On a modern systemd-based Linux distro, this might instead be `if systemctl is-active memcached; then ...`; there are similar tools to query Upstart, launchd, [`runit`](http://smarden.org/runit/), [`daemontools`](https://cr.yp.to/daemontools.html), etc; and they can be set to automatically restart your daemons or trigger arbitrary events if they fail. – Charles Duffy Aug 10 '18 at 16:19
  • 1
    ...keep in mind, too, that `grep memcached` will show up in `grep memcached`. So will `vim memcached.conf`. So `ps auxw | grep` is buggy for other reasons too; `pgrep` is a purpose-built tool that avoids *some* of those bugs. – Charles Duffy Aug 10 '18 at 16:21
  • I'd also suggest making sure you can complete the [exercises in BashFAQ #105](http://mywiki.wooledge.org/BashFAQ/105#Exercises) before using the `-e` argument to bash. It's often a cause of more bugs than it avoids; manual error handling -- pain though it may be to implement -- is an approach less prone to surprises. – Charles Duffy Aug 10 '18 at 16:24

2 Answers2

0

What you're saying here is the output of the debugging -x flag for bash. First it has to run the ps aux, then it has to run the grep .... Then it has to test the results. The [...] test syntax is an expression in itself, and also has to be evaluated.

The + '[' ']' is the representation of that test being performed, shown to you by bash -x.

erik258
  • 14,701
  • 2
  • 25
  • 31
0

It means ps aux | grep -q memcached expanded to an empty string.

If it didn't you'd get what it expanded to.

E.g., ps aux | grep -q memcached prints

++ echo true
+ '[' true ']'
Petr Skocik
  • 58,047
  • 6
  • 95
  • 142