Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In bash shell script how do I convert a string to an number [duplicate]

Tags:

bash

shell

Hey I would like to convert a string to a number

x="0.80"

#I would like to convert x to 0.80 to compare like such:
if[ $x -gt 0.70 ]; then

echo $x >> you_made_it.txt 

fi 

Right now I get the error integer expression expected because I am trying to compare a string.

thanks

like image 322
PJT Avatar asked Nov 23 '09 23:11

PJT


People also ask

What is $@ in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

How do you typecast in Linux?

Let's have a simple illustration of implicit type casting in our Linux system to demonstrate the working of typecasting. So open the command line terminal in the Linux system after logging in. Use “Ctrl+Alt+T” for a quick opening. The GNU editor has been used to write C code so create a quick C language file “one.

How do you copy a variable in shell script?

Show activity on this post. and if you want to reverse the names in the variables: set -- $2 $1 # puts the current "$2" value in "$1", and vice versa, then cp $1 $2 # copies what was file2 contents back to file1.


2 Answers

you can use bc

$ echo "0.8 > 0.7" | bc
1
$ echo "0.8 < 0.7" | bc
0
$ echo ".08 > 0.7" | bc
0

therefore you can check for 0 or 1 in your script.

like image 140
ghostdog74 Avatar answered Oct 12 '22 02:10

ghostdog74


For some reason, this solution appeals to me:

if ! echo "$x $y -p" | dc | grep > /dev/null ^-; then
  echo "$x > $y"
else
  echo "$x < $y"
fi

You'll need to be sure that $x and $y are valid (eg contain only numbers and zero or one '.') and, depending on how old your dc is, you may need to specify something like '10k' to get it to recognize non-integer values.

like image 41
William Pursell Avatar answered Oct 12 '22 01:10

William Pursell