A while ago I bumped into UUOC: [WayBack] cat (Unix): Useless use of cat – Wikipedia.
For me the post important reason to choose between cat and a redirect is realising from the above article:
- input redirection forms allow command to perform random access on the file, whereas the
cat
examples do not. cat
written with UUOC might still be preferred for readability reasons, as reading a piped stream left-to-right might be easier to conceptualize
I ended up at UUOC through [WayBack] bash – Calling multiple commands through xargs – Stack Overflow.
Invoking multiple commands with the same xargs
parameter.
The above question also led me to two better solutions for my original xargs
problem.
I liked both below solutions.
The first (by [WayBack] ckhan) uses sh
as subshell and substitutes the parameter with a readable name.
The second (by [WayBack] shivams) uses a function which gets way more readable code when the command-line gets longer.
[WayBack] shell – xargs : using same argument in multiple commands – Unix & Linux Stack Exchange:
- you’ll want to explicitly execute a subshell:
echo 95 | xargs -n1 -I_percent -- sh -c '[ _percent -ge 95 ] && echo "No Space on disk _percent% full -- remove old backups please"'
Note also I’m using
_percent
instead of{}
to avoid extra quoting headaches with the shell. It’s not a shell variable; still just an xargs replacement string.- An alternative way, which is more readable, is to define a separate function which contains all your other commands and then call that function with
xargs
in a sub-shell.Hence, for example:myfunc(){ [ "$1" -ge 95 ] && echo "No Space on disk $1% full -- remove old backups please" echo "Another command echoing $1" } export -f myfunc echo 95 | xargs -n1 -I_percent -- sh -c 'myfunc "_percent"'
–jeroen