Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign an output to a shellscript variable?

Tags:

shell

pipe

bc

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 
like image 714
GarouDan Avatar asked Apr 18 '13 00:04

GarouDan


People also ask

How do you assign a value to a shell?

Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed. /bin/sh: NAME: This variable is read only.


1 Answers

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).

like image 135
shellter Avatar answered Sep 24 '22 09:09

shellter