shell - How to assign an output to a shellscript variable? -
how assign result shell variable?
input:
echo '1+1' | bc -l
output:
2
attempts:
(didn't work)
#!bin/sh a=echo '1+1' | bc -l echo $a
you're looking shell feature called command-substitution.
there 2 forms of cmd substitution
original, stone-age, portable , available in unix-like shells (well all).
you enclose value generating commands inside of back-ticks characters, i.e.
$ a=`echo 1+1 | bc -l` $ echo $a 2 $
modern, less clunky looking, nestable cmd-substitution supplied
$( cmd )
, i.e.$ a=$(echo 1+1 | bc -l) $ echo $a 2 $
your 'she-bang' line says, #!/bin/sh
, if you're running on real unix platform, it's /bin/sh
original bourne shell, , require use option 1 above.
if try option 2 while still using #!/bin/sh
, works, have modern shell. try typing echo ${.sh.version}
or /bin/sh -c --version
, see if useful information. if version number, you'll want learn features newer shells contain.
speaking of newer features, if using bash, zsh, ksh93+, can rewrite sample code as
a=$(( 1+1 ))
or if you're doing more math operations, stay inside scope, can use shell feature arithmetic like:
(( b=1+1 )) echo $b 2
in either case, can avoid process creation, can't floating point arithmetic in shell (whereas can bc
).
Comments
Post a Comment