2

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?

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

3 Comments

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.
I should also mention, bash -c $string is as bad as eval $string.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.