Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have got this code in file scr.sh:

#!/bin/sh
string='ps -e | less'
$string

And when I execute this script it doesn't work. Why? What I should do to execute command from string variable in shell script?

share|improve this question

1 Answer 1

up vote 4 down vote accepted

It's better to store commands in functions rather than in variables. Functions are great at it. Variables, not at all.

string() {
    ps -e | less
}

string

You could use eval to execute a command that has redirections (>, <) and pipes (|), but I strongly discourage you from doing so.

eval "$string"    # please don't
share|improve this answer
    
Or if it isn't too much to fork then a simple bash -c $string would suffice. Although this method is not as good as a function, it will do the job nonetheless. –  alvits Apr 27 '14 at 19:51
1  
I should also mention, bash -c $string is as bad as eval $string. –  alvits Apr 27 '14 at 20:00
    
Why don't use eval? Only it works in this case. Because really I need to read string from keyboard, doing something with it and then execute. –  dm-kiselev May 7 '14 at 17:13

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.