16

I have command line that outputs a different command line, for example:

> commandlineA param1 param2
  commandlineB param1

I would like to have a single command line execution that will run commandlineB with the given parameter(s).

Is there any simple way to do that using a single command line or do I need to run a small bash file that will store the output in a variable and then run it?

Thanks

1
  • 2
    Searched for quite a while but I guess I had to post a question to find by myself....$(commandlineA param1 param2) did the job.
    – Lior Ohana
    Dec 27, 2015 at 8:48

2 Answers 2

20

You seem to have worked this out yourself, but you can use:

$(command parameter1 parameter2)

Edit of edit: the below is somewhat wrong, whilst it does run the command in a subshell, it turns out that the environment variables will still be available. Sorry for misleading people...

Edit: that will run in a subshell, any unexported environment variables won't be used. If you want to run a command in the same shell, you need to use:

eval $(command parameter1 parameter2)

Another answer given is to pipe through bash itself:

echo 'uname -a' | bash 

That will also execute in a subshell, to run in the same shell you will need:

echo 'uname -a' | bash -c

Incidentally, you can also use back ticks instead of the $() syntax, but it's not recommended.

2
  • (1) I don’t know exactly what you mean by “that will run in a subshell”.  Unexported environment variables will be used. (2) I don’t see any reason to use eval here.  If you have a reason, please explain it.  (3) Your last example (with -c) is totally wrong. Feb 11, 2019 at 19:27
  • You are correct, I checked again and I was wrong there. When running as a list, the bash shell forks and the environment variables are still available. So you are correct, sorry about that. Feb 12, 2019 at 5:55
4

Use this:

commandlineA param1 param2 | bash

Example:

echo "uname -a" | bash

Output:

Linux k1104 2.6.38-8-generic #42-Ubuntu SMP Mon Apr 11 03:31:50 UTC 2011 i686 i686 i386 GNU/Linux
3
  • There's nothing wrong with this, however it will spawn another bash shell. Dec 30, 2015 at 6:02
  • So will $(commandlineA param1 param2)
    – tripleee
    Feb 12, 2019 at 6:22
  • @tripleee: You're comparing oranges and pumpkins.  printf '\143\144\040\057\n' | bash is ultimately a no-op, because the command gets executed in a new, separate (and transient) shell process.  By contrast, $(printf '\143\144\040\057\n') will cause the current, active, interactive shell to change directory. Feb 12, 2019 at 23:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .