Andrew the Programmer
Andrew the Programmer

Reputation: 269

Unable to print newline inside xargs

I'm working on some script to help organize some stuff. I have simplified my code down to this from my original:

$ echo $(find -type d -maxdepth 5 | grep -E "\./([^/])*/([^/])*/([^/])*/([^/])*"
 | cut -d'/' -f 3 | sort | uniq -d | xargs -I R sh -c 'echo -e "alpha \n"')
(R actually doesn't do anything here but it's used in the original)

Particularly, I think something is wrong with my xargs

xargs -I R sh -c 'echo -e "alpha \n"'

What I would look to see happen is alpha to be printed several times, each on a newline. However, my output looks like

alpha alpha alpha...

I've been scouring around the internet trying to find how to fix this but it's no use. I've just started experimenting with bash, can someone please point out what I'm doing wrong?

Upvotes: 0

Views: 268

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295619

This is a special case of I just assigned a variable, but echo $variable shows something else.


Just running a command, no echo:

$ printf '%s\n' "first line" "second line"
first line
second line

Running a command in an unquoted command substitution, as your code is currently written:

$ echo $(printf '%s\n' "first line" "second line")
first line second line

Running a command in a quoted command substitution:

$ echo "$(printf '%s\n' "first line" "second line")"
first line
second line

...so: If you don't have a reason for the outer echo $(...), just remove it; and if you do have a reason, add quotes.

Upvotes: 1

Related Questions