On  2 Nov, Hans-Joerg Bibiko wrote:
>  
>  Dear all,
>  
>  I have the following problem:
>  
>  A command will write some data to STDOUT and, maybe, some data to  
>  STDERR.
>  
>  To assign a variable to STDOUT:
>  
>  A=$(command)
>  
>  To assign a variable to STDERR:
>  
>  B=$(command 2>&1) # redirect STDERR to STDOUT
>  
>  OK
>  
>  But, I want to assign A and B at the same time. But how???
>  
>  One solution would be the following:
>  
>  A=$(command 2>&1 temp.file)
>  B=$(cat temp.file)
>  
>  But I don't want to use a additional temporary file for that.
>  Can I redirect STDOUT or STERR to a variable directly?
>  
>  I would be pleased for any hints.
>  
>  Many thanks in advance
>  
>  Hans

What an excellent question!  Sorry, I don't know.  Nested backtics
sound like what you want, except that then the variable defined in the
inner nesting would not be available to the parent shell.

I thought this (below) should work in sh, but it doesn't.  Looks like an
assignment is not considered a command, unfortunately:

: /home/luke; a=`ls fergel` 2> /dev/null
ls: fergel: No such file or directory

So even if you marked the inner variable as global in scope, this
wouldn't work:

: /home/luke; a=$(b=$(ls fergle) 2>&1)
ls: fergle: No such file or directory

Ah, of course!  Do this (ls is used as an example):

        ls -d /tmp fredldf >/tmp/stdout$$  2> /tmp/stderr$$
        read -r A < /tmp/stdout$$
        read -r B < /tmp/stderr$$
        /bin/rm /tmp/stdout$$ /tmp/stderr$$
        echo "A=$A" "B=$B"

The -r avoids backslash interpretation in case you have arbitrary
output, but is not an option in a traditional Bourne shell - you'd need
a more modern one like bash.

Nice puzzle!

luke

-- 
SLUG - Sydney Linux User's Group Mailing List - http://slug.org.au/
Subscription info and FAQs: http://slug.org.au/faq/mailinglists.html

Reply via email to