fervid
fervid

Reputation: 2123

bash ps comamnd returns error when it executed from string

So, who can explain this behavior:

# rv=$(ps axu | grep logstash | grep -v grep)
# echo $rv
root 6190 8.5 5.9 2248344 242440 pts/0 Sl 16:30 2:09 /usr/bin/java -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -Djava.awt.headless=true -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -Xmx500m -Xss2048k -Djffi.boot.library.path=/opt/logstash-1.5.4/vendor/jruby/lib/jni -XX:+UseParNewGC -XX:+UseConcMarkSweepGC -Djava.awt.headless=true -XX:CMSInitiatingOccupancyFraction=75 -XX:+UseCMSInitiatingOccupancyOnly -Xbootclasspath/a:/opt/logstash-1.5.4/vendor/jruby/lib/jruby.jar -classpath : -Djruby.home=/opt/logstash-1.5.4/vendor/jruby -Djruby.lib=/opt/logstash-1.5.4/vendor/jruby/lib -Djruby.script=jruby -Djruby.shell=/bin/sh org.jruby.Main --1.9 /opt/logstash-1.5.4/lib/bootstrap/environment.rb logstash/runner.rb agent -f /opt/logstash-1.5.4/config/logstash.conf

But:

# cmd="ps axu | grep logs | grep -v grep"
# rv=$($cmd)
error: garbage option

Usage:
 ps [options]

 Try 'ps --help <simple|list|output|threads|misc|all>'
  or 'ps --help <s|l|o|t|m|a>'
 for additional help text.

For more details see ps(1).

And there is no problem without pipes. The following variant works fine:

# cmd="ps axu"
# rv=$($cmd)

Why is there an error if I use a pipe with these commands and execute them as a string?

Upvotes: 0

Views: 1545

Answers (1)

user4832408
user4832408

Reputation:

This can be done using eval. Be warned that this essentially is just taking a bad programming practice and making it worse as eval can open a shell script up to be targeted for arbitrary code execution attacks. Specifically in the case that user arguments are getting evaluated, though filenames could possibly be used to trigger this as well. That being said:

cmd="ls -la | wc"
rv=$(eval $cmd)
echo "$rv"

A more popular and secure practice would be:

cmd1="ls -la"
cmd2="wc"

$cmd1 | $cmd2

Or better yet, one can use functions:

functiona()
{
    ls -la
}

functionb()
{
    wc
}

functiona | functionb

Upvotes: 1

Related Questions