Search code examples
linuxbashshellvariablesxargs

Bash command assigned to variable stays empty


I have few commands following each other after an xargs. Funnily enough the command works fine if just echo it out to stdout. When I try to assign it to a variable, the variable stays empty. See below:

$~ ./somescript | grep -f fc.samples  | xargs -I {} sh -c "echo {} | tr '/' '\t' | cut -f9;"
sample1
sample2
sample3
sample4
sample5
sample6
sample7
sample8
$~

Trying to assign it to a variable and then echo it results in empty lines:

$~ ./somescript | grep -f fc.samples  | xargs -I {} sh -c "sample=$(echo {} | tr '/' '\t' | cut -f9); echo $sample; "







$~

I have tried multiple variations of it and cannot figure out what I am getting wrong. Can somebody spot the problem?

Thanks!


Solution

  • You need to escape the $ chars for the sh -c command, otherwise the $( ) and $sample part will be handled by the current shell rather than the sh -c.

    ... | xargs -I {} sh -c "sample=\$(echo {} | tr '/' '\t' | cut -f9); echo \$sample; "
    

    Or you can consider using single quotes for outer quoting.

    ... | xargs -I {} sh -c 'sample=$(echo {} | tr "/" "\t" | cut -f9); echo $sample; '