[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Bash question: get output as a variable?



On 06.02.2010 14:17, Javier Barroso wrote:
> On Fri, Feb 5, 2010 at 7:10 PM, Chris Jackson <c.jackson@shadowcat.co.uk> wrote:
>> Dotan Cohen wrote:
>>
>>> I'm scripting a backup solution, the line that does the business looks
>>> like this:
>>>
>>> tar -zcvf - *  --exclude-from $EXCLUDES  | openssl des3 -salt -k $1 |
>>> dd of=$(hostname)-$(date +%Y%m%d).tbz
>>>
>>> Because of the "v" flag tar writes to stdout the name of each file
>>> copied. How can I get that output redirected to a variable, to use
>>> later in the script?
>>>
>>> Thanks!
>>>
>>
>>
>> Use $() like you do with the date command. You have to redirect stderr back
>> to stdout, which means running it in a subshell:
>>
>>
>> FILES=$( ( tar -zcvf - *  --exclude-from $EXCLUDES  | openssl des3 -salt -k
>> $1 | dd of=$(hostname)-$(date +%Y%m%d).tbz ) 2>&1 )
>>
>> It may cause unexpected results if there're spaces in the filenames though.
> 
> If there are spaces in filenames, you can try:
> 
> $ n=0; while read l; do files[n]="$l"; ((n++)); done < <((tar -zvcf -
> * | openssl > $(hostname)-$(date +%Y%m%d)) 2>&1)
> 
> Regards,
> 
> 
Warning:

~# read < <(printf "%s\n" " foo bar ")
~# printf "'%s'\n'" "$REPLY"
' foo bar '
~# read l < <(printf "%s\n" " foo bar ")
~# printf "'%s'\n'" "$l"
'foo bar'

read strips of leading and trailing spaces.
use the $REPLY variable to avoid that.

rare conditions of newline in filenames is not covered...

Best regards

Mart



Reply to: