简体   繁体   中英

How to separate outputs of one-line multiple commands?

I have installed some GNU packages on my macOS Sierra, which include bash , coreutils , which , etc. Now I can use which -a bash | xargs -I % echo % "--version" | sh which -a bash | xargs -I % echo % "--version" | sh which -a bash | xargs -I % echo % "--version" | sh to check all version info of bash , but there is no separation between two version info:

$ which -a bash | xargs -I % echo % "--version" | sh
GNU bash, version 4.4.12(1)-release (x86_64-apple-darwin16.3.0)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
# There should be one or more blank lines as separation.
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin16)
Copyright (C) 2007 Free Software Foundation, Inc.

I tried ... echo -e % "--version\\n" ... , but it can't work. Please help me, thanks.

For a bit more control of the output, use a loop:

which -a bash |
while read cmd; do
    printf '%s\t----------\n' "$cmd"
    command "$cmd" --version
    echo
done

I'd write this as follows:

IFS=: read -r -a path_entries <<<"$PATH"
find "${path_entries[@]}" -maxdepth 1 -name bash -type f -exec '{}' --version ';'

Note:

  • No use of which . This isn't a shell builtin in bash, so it gives you none of the benefits you'd get from type (ie. awareness of functions and aliases); and because its output is line-oriented, it can't unambiguously emit all possible filenames (such as those containing newlines -- which, yes, are valid).
  • No reliance on line-oriented content, generally. When the placeholder ( {} ) is passed as a single token, find -exec substitutes the exact filename returned for that token. Because the domain of possible argv values (all valid C strings, which is to say, no strings containing NULs) matches the domain of possible filenames on common systems, this avoids introducing potential bugs.
  • No generating text and piping that to an interpreter. This is an extremely error-prone technique, inducing shell-injection vulnerabilities: Consider what would happen if a PATH contained /tmp/$(rm -rf ~) , and that directory contained a bash executable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM