Assuming user has 5 processes started, what is queried with below sentences:

a="`ps -C process -o user= | grep $cuser`"
echo $a
user user user user user


echo "`ps -C process -o user= | grep $cuser`"

Then it looks like in the 1st case the 'newline' or '\n' is converted to spaces, which seems a good idea.

It looks hard to see how space and newlines are handled in the shell in different situations.

It might need a complete manual for checking how spaces and newlines are handled in each occasion.

Any advice for how they are handled in each occasion?

Here pls. notice that 'newline' is converted into 'space'.

echo "$a" would then seem to preserve the newlines. This is then maybe echo-command properties to convert newlines to spaces.

  • 1
    The shell subjects echo $a to word splitting which converts all runs of whitespace to a single blank. The use of double-quotes, as in echo "$a", would suppress that.
    – John1024
    Aug 2 '19 at 6:33

Don't trust echo; use declare -p to inspect a variable's contents.

In short:

  • Quoted strings (including any sort of variable expansions within double-quotes) preserve all whitespace. The entire string is sent as a single argument to echo.

    $ foo="one   two 'three four'"
    $ ~/bin/args "$foo"
    argv[0] = args
    argv[1] = one   two 'three four'
    $ ~/bin/args '$foo'
    argv[0] = args
    argv[1] = $foo
  • Unquoted strings or expansions are subject to word-splitting; each IFS-separated word becomes a separate argument given to echo, and the echo command re-joins all its arguments using a single space as separator.

    $ foo="one   two 'three four'"
    $ ~/bin/args $foo
    argv[0] = args
    argv[1] = one
    argv[2] = two
    argv[3] = 'three
    argv[4] = four'
  • The right-hand side of variable assignments is an exception to the rule; expansions therein always work as if they were double-quoted. These are equivalent:

    foo=$(ps ...)
    foo="$(ps ...)"
    foo=`ps ...`
    foo="`ps ...`"

    (Array assignments like foo=(...) are an exception to the exception and each array item needs to be quoted again.)

See also:

  • There are plenty of other threads about newlines in $var, but all of them just tell you to use quotes and don't really explain anything else at all.
    – user1686
    Aug 2 '19 at 6:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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