macron0 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks,

How do I get the output from a sudo command using backticks.

If I do this:

$result=`sudo ls -la`; print "$result\n";

I get the sudo output:

sudo: please use single character options usage: sudo -K | -L | -V | -h | -k | -l | -v usage: sudo [-HPSb] [-p prompt] [-u username|#uid] { -e file [...] | -i | -s | <command> }

If I do this:

$result=`sudo ls -la`; print "$result\n";

I get nothing at all.

It seems such a simple question but I cannot find the answer.

So I was wondering if anyone here might know the answer.

I really need to parse the output of some scripts and I also need to use sudo.

Thank you.

Hans de Groot

Replies are listed 'Best First'.
Re: Capture output from backtick commands using sudo
by afoken (Chancellor) on Apr 04, 2010 at 12:06 UTC

    Your example works for me, and I fail to see a difference between

    $result=`sudo ls -la`; print "$result\n";

    and

    $result=`sudo ls -la`; print "$result\n";

    . The first error message looks like you have placed the ls options before the ls command. Show us the real code that fails, copied and pasted into <code> tags.

    Alexander

    --
    Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
Re: Capture output from backtick commands using sudo
by ww (Archbishop) on Apr 04, 2010 at 12:34 UTC
      Hi, I stumbled across the same issue as you. In fact, since sudo will return: 'Upon successful execution of a program, the exit status from sudo will simply be the exit status of the program that was executed.' - you will not the the result of the 'ls'. In a specific case, what I wished for was the output of the executed program ('ls', for you). Did you find an answer for this? I'd really prefer not to use any temp files. Thanks! Norbert

        Huh? Give perl -E 'say `sudo "/bin/ls"`' a try. The exit status is not the STDOUT of the programme, but it's "return code". Like: did the command succeed?

        Cheers, Sören

        Créateur des bugs mobiles - let loose once, run everywhere.
        (hooked on the Perl Programming language)