Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
xargs-expander
#!/bin/bash
# a confirm utility for use with xargs
# we read the arguments up to the "--" as the command to run.
# and then everything after the "--" is interpreted as an argument to the thing before the "--"
# input="$@"
# echo "input: ${input}"
cmd=""
cmd_read=0;
args="";
while [[ $# -gt 0 ]]
do
key="${1}"
if [ ${key} == "--" ]; then
# we are done reading things in for the cmd
cmd_read=1;
else
if [ ${cmd_read} -eq 0 ]; then
cmd="${cmd} ${key}";
else
args="${args} ${key}";
fi;
fi;
shift;
done
# echo "cmd: ${cmd}"
# echo "args: ${args}"
for arg in ${args}; do
echo "${cmd} ${arg}";
# echo "OK? [Y]/n";
# read response;
# case ${response} in
# y|Y)
# echo "Running ${cmd} ${arg}";
# eval "${cmd} ${arg}";
# ;;
# *)
# echo "NOT Running ${cmd} ${arg}";
# ;;
# esac;
done
@travishein

This comment has been minimized.

Copy link
Owner Author

travishein commented Jun 18, 2019

This came up from a discussion of wanting to confirm each option in an xargs invocation.

The challenge here is we are not able to read a confirm message in our script, as the STDIN is pipe connected to the output from xargs.

What we can opt to do instead is enumerate the things passed into this script, expanding them as some command then the thing from xargs.

Here we use the "--" to delimit the end of the command and the start of the things from xargs.

One caveat here is we lose the formatting of things with spaces in it. If for example the input is

ls -1 | xargs ./confirm.sh ls -l --

then files read in with spaces in them will be broken up into multiple invocations of the cmd here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.