I have a file which contains only one large number. I need to save this number in an integer variable in order to use it in mathematical operations.
I've tried: var=$(<filename) but it saves it as string.
There are no integer variables in common shellscript (bash, sh) -- all variables are either strings or arrays. So just use the variable normally:
$ echo 2 > test
$ X=$(< test)
$ Y=$(($X + 2))
$ echo $Y
4
expr $num / 2 ] do if [ expr $num % $i -eq 0 ] then f=1 fi i=expr $i + 1 done if [ $f -eq 1 ] then echo "The number is composite" else echo "The number is Prime" fiIf I understand you are attempting to read the value from a file and check whether it is prime or not, your problem isn't the value in the file. The problem is your shell syntax. Following along from your questions and comments, it looks like you are trying to do the following:
#!/bin/sh
num=$(<"$1")
i=2
f=0
while [ $i -le $(expr $num / 2) ]; do
if [ $(expr $num % $i) -eq 0 ]; then
f=1
fi
i=$(expr $i + 1)
done
if [ $f -eq 1 ]; then
echo "The number is composite"
else
echo "The number is Prime"
fi
Use/Output
$ cat dat/pnumber.txt
31
$ sh prime.sh dat/pnumber.txt
The number is Prime
$cat dat/npnumber.txt
32
$ sh prime.sh dat/npnumber.txt
The number is composite
The problem was you failed to recognize that expr is a separate command and must be enclosed in either backticks or $() to return the value of the expression to a variable or use it in test constructs.
If you would rather use the older backtick command substitution syntax, then the following is equivalent to what is shown above:
while [ $i -le `expr $num / 2` ]; do
if [ `expr $num % $i` -eq 0 ]; then
f=1
fi
i=`expr $i + 1`
done
I had to use python calculations because float are not supported in bash arithmetics:
CPU_TEMPERATURE_fOffset=/sys/bus/iio/devices/iio:device0/in_temp0_offset
CPU_TEMPERATURE_fScale=/sys/bus/iio/devices/iio:device0/in_temp0_scale
alias QA_READ_ZINQ_TEMP="echo -n "fRaw="; sudo cat $CPU_TEMPERATURE_fRaw;echo -n "fOffset=";sudo cat $CPU_TEMPERATURE_fOffset;echo -n "fScale=";sudo cat $CPU_TEMPERATURE_fScale;"
F_QA_ZINQ_TEMP_DIAG()
{
QA_READ_ZINQ_TEMP
echo "Calculating temperature using formula: ((raw + offset) * scale) / 1000"
raw=$(< $CPU_TEMPERATURE_fRaw)
offset=$(< $CPU_TEMPERATURE_fOffset)
scale=$(< $CPU_TEMPERATURE_fScale)
echo -n "Temperature is: "
python_command="print((($raw+$offset)*$scale)/1000)"
python3 -c $python_command
}
alias QA_ZINQ_TEMP_DIAG=F_QA_ZINQ_TEMP_DIAG
Using it worked for me:
$ QA_ZINQ_TEMP_DIAG
fRaw=2536
fOffset=-2219
fScale=123.040771484
Calculating temperature using formula: ((raw + offset) * scale) / 1000
Temperature is: 39.742169189332
declare -i var=$(<file)(assuming bash), but that does not gain you a whole lot.filename, you get it invar. You can confirm withprintf " int: '%d' string: '%s' var-1 : '%d'\n" "$var" "$var" $((var - 1))