0

Using the -d flag in xargs to specify a delimter seems to tack an newline after the last value. Either way, it causes the command to break when using substitution to stick the value into the middle of the command (vs the more "standard" way of having xargs pass the value to the very end of the command).

To rephrase, this only happens when using -d and -I flags and sticking the values into the middle of the command.

How can I fix this?

Example:

# echo "server1 server2 server3 server4"|xargs -r -d" " -I+ echo ssh + "sudo service myservice restart"
ssh server1 sudo service myservice restart
ssh server2 sudo service myservice restart
ssh server3 sudo service myservice restart
ssh server4
 sudo service myservice restart

Note the last command is offset by a newline. This would not be a problem if the command ended at the newline, but in this case it does not.

I've worked around this by tacking " null" to the end of the list I pass to xargs, and ignoring the resulting error. But that is a lousy solution, and dangerous in some cases.

My workaround:

# echo "server1 server2 server3 server4 null"|xargs -r -d" " -I+ echo ssh + "sudo service myservice restart"
ssh server1 sudo service myservice restart
ssh server2 sudo service myservice restart
ssh server3 sudo service myservice restart
ssh server4 sudo service myservice restart
ssh null
 sudo service myservice restart
JDS
  • 1,869
  • 1
  • 15
  • 17

1 Answers1

1

xargs isn't tacking on a newline; it's just that since newline isn't a delimiter anymore, the newline that was already in your input is taken literally.

If you're actually using echo to supply the input to xargs, use echo -n so that it doesn't add a newline. If you're using something other than echo, investigate how you can get it to not add a trailing newline, or remove the newline using tr or sed or perl or something.

hobbs
  • 223,387
  • 19
  • 210
  • 288