Search code examples
bashnewlineecho

Bash: print each input string in a new line


With xargs, I give echo several strings to print. Is there any way to display each given string in a new line?

find . something -print0 | xargs -r0 echo

I'm sure this is super simple, but I can't find the right key words to google it, apparently.


Solution

  • find . something -print0 | xargs -r0 printf "%s\n"
    

    Clearly, find can also print one per line happily without help from xargs, but presumably this is only part of what you're after. The -r option makes sense; it doesn't run the printf command if there's nothing to print, which is a useful and sensible extension in GNU xargs compared with POSIX xargs which always requires the command to be run at least once. (The -print0 option to find and the -0 option to xargs are also GNU extensions compared with POSIX.)

    Most frequently these days, you don't need to use xargs with find because POSIX find supports the + operand in place of the legacy ; to -exec, which means you can write:

    find . something -exec printf '%s\n' {} +
    

    When the + is used, find collects as many arguments as will fit conveniently on a command line and invokes the command with those arguments. In this case, there isn't much point to using printf (or echo), but in general, this handles the arguments correctly, one argument per file name, even if the file name contains blanks, tabs, newlines, and other awkward characters.