Neil
Neil

Reputation: 9463

How would you execute a command stored as a string in one line of bash

How would you execute a command stored as a string in one line of bash. For example this doesn't work but I want to do something similar.

echo "uname -a" | eval

Is it possible to do this or would I have to create a bash script?

Update

I'm using boom to store some one line command line statements. I want to be able to get them and execute them. Something like this:

boom echo name | eval

Upvotes: 1

Views: 419

Answers (4)

tripleee
tripleee

Reputation: 189926

If you want to use echo specifically and don't mind spawning a subshell, echo "uname -a" | sh works.

Upvotes: 3

anubhava
anubhava

Reputation: 786101

You can use bash -c option like this:

bash -c "your-string-with-shell-commands"

eg:

bash -c "dirname $PWD/foo"

Upvotes: 0

Dimitre Radoulov
Dimitre Radoulov

Reputation: 28010

s='<your_string>'
eval "$s"

Note that usually there is a better approach in such cases (i.e. most probably you don't need eval).

Upvotes: 2

user647772
user647772

Reputation:

#!/bin/sh
s="date +%Y-%m-%d"
$s

Executing this script prints 2012-02-01.

Upvotes: 1

Related Questions