Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I was wondering why this command line does not print pidof sh

$ sh -c "var=`pidof sh` ; echo \$var; ps -H"

This one prints 123 as expected

$ sh -c "var=123 ; echo \$var; ps -H"

I am on ubuntu linux

share|improve this question
add comment

1 Answer 1

up vote 4 down vote accepted

You miss the quotes. One way to do it:

sh -c "var=\"`pidof sh`\" ; echo \$var; ps -H"

Another:

sh -c "var=\"\`pidof sh\`\" ; echo \$var; ps -H"

Notice that they differ in the moment when the pidof sh is executed! In the first version, the expression within backticks (pidof sh) is executed by your current shell - that is before sh -c is run. In the second, it is the sh -c command that executes pidof. More than that, the pidof is executed within a subshell that evaluates the expression within backticks - so you get one additional pid listed in the var variable. (Put it more simple: the backticks invoke another shell which is then listed by pidof.)

A better way for both would be to use $( ... ) or \$( ... ).

share|improve this answer
    
Thanks that worked. But I don't understand what do you mean when you say "Notice that they differ in the moment when the pidof sh is executed!" –  abc Aug 28 '11 at 0:01
    
Also why do I get two pids listed on printing $var. I that for pidof program? –  abc Aug 28 '11 at 0:02
1  
This is because at the time when pidof is executed, a second sh is running (a subshell) in order to evaluate what is between the backticks. –  rozcietrzewiacz Aug 28 '11 at 0:23
3  
@abc I suspect you meant to write sh -c 'var=$(pidof sh); echo $var; ps -H'. With the double quotes, as rozcietrzewiacz said, the pidof command was executed to build the string that is passed to sh. With single quotes, the text between the quotes is passed to sh as is. –  Gilles Aug 28 '11 at 9:39
    
Thanks for the answers!! –  abc Aug 28 '11 at 19:17
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.