ramfree17
ramfree17

Reputation: 79

How to set a bash variable in a compound xargs statement

I am looking for a way to set a variable in the statements passed to xargs. The value is to be manipulated in one of the commands. Using a file or another utility is an option but I am not sure why setting the bash variable in the sequence is always coming up as empty.

$ ls c*txt
codebase.txt  consoleText.txt

$  ls c*txt | xargs -i bash -c "echo processing {}; v1={} && echo ${v1/txt/file}"
codebase.txt  consoleText.txt

processing codebase.txt

processing consoleText.txt

The example above distills the question to the basics. I was expecting the behavior to be something like this but inline:

$ fname=codebase.txt; echo ${fname/txt/file}
 codebase.file

Thank you.

Upvotes: 0

Views: 3926

Answers (1)

Jerry Jeremiah
Jerry Jeremiah

Reputation: 9618

This line is resolving ${v1/txt/file} to a value before the command is executed:

$  ls c*txt | xargs -i bash -c "echo processing {}; v1={} && echo ${v1/txt/file}"

And that means the bash -c doesn't even see ${v1/txt/file}

In this line the single quotes inhibit the variable substitution so echo processing {}; v1={} && echo ${v1/txt/file} is actually passed to bash -c as a parameter:

$  ls c*txt | xargs -i bash -c 'echo processing {}; v1={} && echo ${v1/txt/file}'

You could accomplish the same thing by escaping the dollar sign:

$  ls c*txt | xargs -i bash -c "echo processing {}; v1={} && echo \${v1/txt/file}"

Upvotes: 5

Related Questions