Shell – How to read the output of commands in a script

command-substitutionshell-script

I'm learning Linux scripting at the moment, and one thing I can get working is assigning a command output to a variable. The command service httpd configtest returns Syntax is OK, so I wrote this.

#!/bin/bash

var=`service httpd configtest`
echo "Output is $var"

From what I've read that should store the output in var, then echo it. However, the output when I run that script is

Syntax OK
Output is

What have I done wrong? I'm using CentOS 6.5 if that makes a difference.

Best Answer

When you run service httpd configtest, it actually run command apachectl configtest:

  ....
  apachectl=/usr/sbin/apachectl  
  ....
  graceful|help|configtest|fullstatus)
        $apachectl $@
        RETVAL=$?
        ;;
  ....

Do a strace:

$ strace -f -e trace=write apachectl configtest
Process 22999 attached (waiting for parent)
Process 22999 resumed (parent 22998 ready)
[pid 22999] write(1, "1024\n", 5)       = 5
Process 22999 detached
--- SIGCHLD (Child exited) @ 0 (0) ---
Process 23000 attached (waiting for parent)
Process 23000 resumed (parent 22998 ready)
Process 22998 suspended
[pid 23000] write(2, "Syntax OK\n", 10Syntax OK
) = 10
Process 22998 resumed
Process 23000 detached
--- SIGCHLD (Child exited) @ 0 (0) ---

You can see, the output Syntax OK is written to stderr, causes the ouput can not save to var variable.

You can make it done, by redirect stderr to stdout:

var=$(service httpd configtest 2>&1)
Related Question