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?
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
bash -c $string would suffice. Although this method is not as good as a function, it will do the job nonetheless.bash -c $string is as bad as eval $string.eval? Only it works in this case. Because really I need to read string from keyboard, doing something with it and then execute.