syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me

You are here: Linux101 > Shell 101 > shell101_whileloop

Linux Shell 101

Question:
In Shell101 how to write Bash while-loop?

I will expand the above question:

In Shell101 how to write Bash script which has a while-loop, grep, float variables, cut, and bc?

In this demo I want to use simple shell syntax to do arithmetic on float variables.
#!/bin/bash

# ~ann/whileloop_gspc.bash

# This script should work on a CSV file from Yahoo with a while-loop.

# I should cd to the right folder:

cd ~ann

export TKR=GSPC

# Assume that ${TKR}4.csv was just built and it has these columns
# Date, Close, date_lag, close_lag

# I should build a CSV which has these columns:
echo 'cdate, cp, lag_date, lag_price, delta, pctg' > ${TKR}5.csv

echo I am busy, please wait ...

# In Bash undeclared variables are strings.
# I should declare to Bash that I will use variables which hold float numbers:
declare -f current_price previous_price delta pctg

grep -v Date ${TKR}4.csv | while read line 
do
  current_price=`echo  $line|cut -d, -f2`
  previous_price=`echo $line|cut -d, -f4`
  delta=`echo $current_price - $previous_price | bc`
  pctg=`echo "scale=4; 100.0 * $delta / $previous_price" | bc`
  echo $line , $delta , $pctg >> ${TKR}5.csv
done

echo I am done, I created ${TKR}5.csv from ${TKR}4.csv
echo Here look:

head ${TKR}5.csv

exit
When I run the above script I see this:
ann@feb ~ $ 
ann@feb ~ $ 
ann@feb ~ $ ./whileloop_gspc.bash
I am busy, please wait ...
I am done, I created GSPC5.csv from GSPC4.csv
Here look:
cdate, cp, lag_date, lag_price, delta, pctg
2015-02-20,2110.30 , 2015-02-19,2097.45 , 12.85 , .6126
2015-02-19,2097.45 , 2015-02-18,2099.68 , -2.23 , -.1062
2015-02-18,2099.68 , 2015-02-17,2100.34 , -.66 , -.0314
2015-02-17,2100.34 , 2015-02-13,2096.99 , 3.35 , .1597
2015-02-13,2096.99 , 2015-02-12,2088.48 , 8.51 , .4074
2015-02-12,2088.48 , 2015-02-11,2068.53 , 19.95 , .9644
2015-02-11,2068.53 , 2015-02-10,2068.59 , -.06 , -.0029
2015-02-10,2068.59 , 2015-02-09,2046.74 , 21.85 , 1.0675
2015-02-09,2046.74 , 2015-02-06,2055.47 , -8.73 , -.4247
ann@feb ~ $ 
ann@feb ~ $ 


So, that is the sixth shell programming demo of shell101.



You are here: Linux101 > Shell 101 > shell101_whileloop
You can ask questions in Dan's Machine Learning Class Forum:
https://groups.google.com/forum/#!forum/dan101

syntax.us Let the syntax do the talking
Blog Contact Posts Questions Tags Hire Me