How to assign an output to a shellscript variable?
Asked Answered
P

1

29

How to assign this result to a shell variable?

Input:

echo '1+1' | bc -l

Output:

2

Attempts:

(didn't work)

#!bin/sh
a=echo '1+1' | bc -l
echo $a
Peddle answered 18/4, 2013 at 0:2 Comment(1)
possible duplicate of How to set a BASH variable equal to the output from a command?Armbruster
G
58

You're looking for the shell feature called command-substitution.

There are 2 forms of cmd substitution

  1. Original, back to the stone-age, but completely portable and available in all Unix-like shells (well almost all).

    You enclose your value generating commands inside of the back-ticks characters, i.e.

    $ a=`echo 1+1 | bc -l`
    $ echo $a
    2
    $
    
  2. Modern, less clunky looking, easily nestable cmd-substitution supplied with $( cmd ), i.e.

    $ a=$(echo 1+1 |  bc -l)
    $ echo $a
    2
    $
    

Your 'she-bang' line says, #!/bin/sh, so if you're running on a real Unix platform, then it's likely your /bin/sh is the original Bourne shell, and will require that you use option 1 above.

If you try option 2 while still using #!/bin/sh and it works, then you have modern shell. Try typing echo ${.sh.version} or /bin/sh -c --version and see if you get any useful information. If you get a version number, then you'll want to learn about the extra features that newer shells contain.

Speaking of newer features, if you are really using bash, zsh, ksh93+, then you can rewrite your sample code as

a=$(( 1+1 ))

Or if you're doing more math operations, that would all stay inside the scope, you can use shell feature arithmetic like:

(( b=1+1 ))
echo $b
2

In either case, you can avoid extra process creation, but you can't do floating point arithmetic in the shell (whereas you can with bc).

Golter answered 18/4, 2013 at 0:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.