4

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.

Gilles 'SO- stop being evil'
  • 807,993
  • 194
  • 1,674
  • 2,175
TMH
  • 427
  • 6
  • 14

3 Answers3

7

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)
cuonglm
  • 150,973
  • 38
  • 327
  • 406
5

My guess is that the service httpd configtest is outputting to stderr instead of stdout. You could try:

var=$(service httpd configtest 2>&1)
echo "Output is $var"

Or even this, without the variable:

echo -n "Output is "
service httpd configtest 2>&1

The -n option to echo suppresses the newline at the end so that the output of service httpd configtest will be on the same line.

Also note I have switched the backticks (`...`) for $(...) above since backticks can cause some problems and are generally considered deprecated. See What's the difference between $(stuff) and `stuff`? for more information.

For more information on what stdout and stderr are and what 2>&1 does, check out the Wikipedia pages on Standard Streams and Redirection.

Graeme
  • 33,607
  • 8
  • 85
  • 110
2

The variable var contains ANSI escape codes that causes it to move a line up.

Your output can be reproduced with the following example:

var=$'\033[FSyntax OK\n'
echo "Output is $var"

This produces:

Syntax OK
Output is

where the first line overwrites the prompt from which the script (containing the above two lines was started).

devnull
  • 10,541
  • 2
  • 40
  • 50