Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.


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.

share|improve this question
up vote 7 down vote accepted

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

        $apachectl $@

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)
share|improve this answer

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.

share|improve this answer

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).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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