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
add comment

1 Answer

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 2 days ago
1  
I should also mention, bash -c $string is as bad as eval $string. –  alvits 2 days ago
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.