Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot use env variables in xargs

Tags:

bash

sh

xargs

Team, I cannot see variable substitution while performing xargs command. any hint, how to replace $hostname? on my system hostname is a command and not a variable defined in env. But i can set it to variable also..

hostname="$(hostname)"

ls -ltr /var/log/console.* | awk -F 'log/' '{print $2}' | xargs - 
l1 -- sh -c 'aws s3 cp /var/log/"$1" s3://test- 
bucket/dom0/$hostname/' --

output

upload: ../var/log/console.68.log to s3://test- 
bucket/dom0//console.68.log

Please observe dom0// above it should be

expected

dom0/host-123/console.68.log

1 Answers

You can safely and easily pass the hostname as a positional parameter in the same way that you pass the filename argument:

hostname="$(hostname)"

ls -ltr /var/log/console.* | awk -F 'log/' '{print $2}' | xargs - 
l1 -- sh -c 'aws s3 cp "/var/log/$2" "s3://test-bucket/dom0/$1/"' -- "$hostname"

This eliminates the fragile injection of variables or filenames into the shell string.

like image 170
that other guy Avatar answered Aug 14 '26 10:08

that other guy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!