1

I have a CLI program that generates arguments as one string for another CLI program. I call both from BASH. Here is simplified version of what I have:

produce_args() {
    echo "arg1 \"ar g2\" arg3"
}

consume_args() {
    for arg in "$@"; do
        echo "$arg"
    done
}

TMP="$(produce_args)"
consume_args $TMP

It prints:

arg1
"ar
g2"
arg3

So, argument 2 was split to two arguments. How to see an output like this instead?

arg1
ar g2
arg3

I can change my generator CLI program and BASH script but not consumer program. Also I can use zsh but I don't really think that matters in my case.

2 Answers 2

2

I'd abstain from using eval as much as possible, albeit I don't mind using it if necessary. In your case I'd probably use a new-line as arg-separator, modify IFS accordingly, and make TMP an array:

#!/bin/bash
produce_args() {
        echo -e "arg1\nar g2\narg3"
}
consume_args() {
        for arg in "${@}"; do
                echo "$arg"
        done
}
NL="
"
OLDIFS="${IFS}"
IFS="${NL}"
declare -a TMP
TMP=($(produce_args))
IFS="${OLDIFS}"
consume_args "${TMP[@]}"
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your solution!
0

You can use 'eval' to on the call to consume_args. It will allow the shell to process in the quoted string from the produce args as a single argument:

#! /bin/bash

produce_args() {
    echo "arg1 \"ar g2\" arg3"
}

consume_args() {
    for arg in "$@"; do
        echo "$arg"
    done
}

TMP="$(produce_args)"
eval consume_args $TMP

2 Comments

Oh, gosh, man! That simple! It's a terrible answer :( Thank you a lot!
This is just asking for problems when produce_args changes. Consider, for example, if the output of produce_args produces an argument with more than one consecutive whitespace.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.