xargs builds and executes command lines from standard input.
While pipe command (|) takes the stdout of the previous command and forwards it to stdin of the next command, xargs takes space-separated strings from that stdin and convert them into arguments of xargs command.
Example:
$ echo "/dirA /dirB" | xargs ls
will be converted to:
ls /dirA /dirB
-n1 causes the command specified by xargs to be executed, taking one argument at a time from its input (arguments can be each in one line or simply separated by spaces or tabs) and running the command separately for each individual item. The -n1 option means "use just one argument per command invocation". Each item from standard input (for example, a filename from a list) will be passed separately to the command. As a result, the command will be run as many times as there are items in the input, once for each.
Example:
echo -e "a\nb\nc" | xargs -n1 echo
...will produce:
echo a
echo b
echo c
So each invocation receives only one argument from the input.
This is useful when a command should process only one item at a time, such as deleting files one by one, or when handling commands that cannot accept multiple arguments simultaneously.
-I{} replaces {} in the command with the input item (in the following example that's lambda function name).
In the following example we use -I to replace {} with incoming argument for xarg and then we use $ positional parameters to interpolate inputs for sh:
Let's assume we have previously defined variables like...
AWS_PROFILE=...
AWS_REGION=...
SG_ID=...
aws lambda list-functions \
--profile "$AWS_PROFILE" \
--region "$AWS_REGION" \
--query "Functions[].FunctionName" \
--output text | \
xargs \
-n1 \
-I{} \
sh -c \
"aws lambda get-function-configuration \
--profile \"\$1\" \
--region \"\$2\" \
--function-name \"\$3\" \
--query \"VpcConfig.SecurityGroupIds\" \
--output text 2>/dev/null | \
grep \
-w \"\$4\" && \
echo \
\"Found in Lambda function: \$3\"" \
_ "$AWS_PROFILE" "$AWS_REGION" {} "$SG_ID"
The sh -c command allows passing multiple arguments, which are referenced as $1, $2, $3, and $4 inside the shell script.
The underscore (_) is used as a placeholder for the $0 positional parameter inside the sh -c subshell.
When you use sh -c 'script' arg0 arg1 arg2 ..., the first argument after the script (arg0) is assigned to $0 inside the script, and the rest (arg1, arg2, etc.) are assigned to $1, $2, etc.
In this context, _ is a common convention to indicate that the $0 parameter is not used or is irrelevant. It simply fills the required position so that $1, $2, $3, and $4 map correctly to "$AWS_PROFILE", "$AWS_REGION", {} (the function name), and "$SG_ID".
No comments:
Post a Comment