3

I am wondering if it is possible in BASH to use commands in this way:

lets take command pwd

Lets say I would like to have a variable comm="pwd" and then use it somewhere in program, but when I use it, I get the real pwd command output. Is this even possible?

user1926550
  • 539
  • 5
  • 10
  • 18
  • 1
    Yes, you can do it — see the [answer](http://stackoverflow.com/a/16133694/15168) by [hek2mgl](http://stackoverflow.com/users/171318/hek2mgl). In this simple case with a command and no arguments, it is straight-forward. A command with simple space-less arguments is also OK. If the command needs to preserve spaces in arguments, it is anything but straight-forward and there are probably better ways to do it. – Jonathan Leffler Apr 21 '13 at 17:22

3 Answers3

2

It's pretty simple, you can just do:

comm='pwd'
# just execute
$comm
# fetch output into variable
output=$($comm)
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
1

Try doing this :

var=$(pwd)

The backquote (`) is used in the old-style command substitution, e.g.

foo=`command`

The

foo=$(command)

syntax is recommended instead. Backslash handling inside $() is less surprising, and $() is easier to nest. See http://mywiki.wooledge.org/BashFAQ/082

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
  • But this: var="$(ps -e -o "pid comm %mem user %cpu" --sort -%cpu | head -n 11)" doesnt give the same output as this: ps -e -o "pid comm %mem user %cpu" --sort -%cpu | head -n 11 – user1926550 Apr 21 '13 at 17:02
  • 1
    You need quotes on the variables like `echo "$var"` – Gilles Quénot Apr 21 '13 at 17:03
  • "USE MORE QUOTES!" and "Double quote" _every_ expansion, as well as anything that could possibly contain a special character, e.g. "$var", "$@", "${array[@]}", "$(command)". Bash treats everything within 'single quotes' as literal. Learn the difference between ' and " and `. See http://mywiki.wooledge.org/Quotes, http://mywiki.wooledge.org/Arguments and http://wiki.bash-hackers.org/syntax/words – Gilles Quénot Apr 21 '13 at 17:04
  • 1
    Have you read the question? `Lets say I would like to have a variable comm="pwd" and then use it somewhere in program` .. Means not `use its output somewhere in program` – hek2mgl Apr 21 '13 at 17:05
  • @hek2mgl: It's not clear after reading again OP question what is really asked here – Gilles Quénot Apr 21 '13 at 17:09
  • I think it is clear. OP wants to store a command in a variable and execute it later. Can you please test my example using `bash example.sh` and tell me again that it `doesn't anything` ? – hek2mgl Apr 21 '13 at 17:10
0

Yes, just surround the sub-command in backticks (the ` character):

comm=`pwd`
Stuart M
  • 11,458
  • 6
  • 45
  • 59