How not to print a new line with echo (and wc) in a shell script?

I have done this script :

#! /bin/sh  
path="foo" 
while touch $path ; do 
    path=./${path} 
done 

echo "echec avec le nom $path qui fait" 
echo $path|wc -c 
echo "caracteres"

How can I print on the same line the 3 echo lines?

Asked By: user3581976

||

The -n option with echo suppresses newline. So, you can do:

echo -n "echec avec le nom $path qui fait" 
echo -n $(echo $path|wc -c)
echo "caracteres"
Answered By: unxnut

To suppress the newline with the echo used on linux systems1, use -n:

echo -n "echec avec le nom $path qui fait"

However, wc also prints a newline, and that can’t be suppressed, but it can be discarded:

size=$(echo $path | wc -c);
echo "echec avec le nom $path qui fait $((size-1)) caracteres"

I’ve used $((size-1)) here because wc will have counted the newline output by echo. You could instead use size=$(echo -n $path | wc -c), but beware the caveat about the non-standardness of -n.


1. The -n implemented by GNU coreutil’s echo is non-standard, so YMMV. Fortunately, you don’t actually need to use it here.

Answered By: goldilocks

It would be far better if you didn’t use echo at all. The use of echo when combined with arbitrary input can have unintended effects. What’s more, you do not need wc to count the characters in a shell variable – the shell can do it just as well and without execing a separate process to boot.

For example:

with wc:

_path=/some/place/in/my/filesystem
printf %s "$_path" | wc -c

###OUTPUT###
28

no wc:

printf %s "${#_path}"

###OUTPUT###
28

two printf arguments:

printf 'Arg char count:t%snArg contents:t%sn'                                                                     
    "${#_path}" "$_path"

###OUTPUT###
Arg char count: 28
Arg contents:   /some/place/in/my/filesystem

your command:

printf 'echec avec le nom %s qui fait %s caracteresn' 
    "$_path" "${#_path}"

###OUTPUT###
echec avec le nom /some/place/in/my/filesystem qui fait 28 caracteres

See Why is printf better than echo? and the spec on POSIX parameter expansion for more information.

Answered By: mikeserv
Categories: Answers Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.