(standard_in) 1: syntax error in bash script - bash

I'm trying to generate some quasi random numbers to feed into a monte carlo simulation. I'm using bash. I seem to have hit a syntax error which I've narrowed down to being in this bit of code.
randno4=($RANDOM % 100001)
upper_limit4=$(echo "scale=10; 1*75.3689"|bc)
lower_limit4=$(echo "scale=10; 1*75.1689"|bc)
range4=$(echo "scale=10; $upper_limit4-$lower_limit4"|bc)
t_twall=`echo "scale=10; ${lower_limit4}+${range4}*${randno3}/100001" |bc`
echo "$t_twall"
Does anyone know why I the below output and not a value between 75.3689 and 75.1689 as that is what I would be expecting?
(standard_in) 1: syntax error

The first line should looks like :
randno4=$((RANDOM % 100001))
(( )) is bash arithmetic, with the leading $ , the value is substituted : $(( ))
When you wrote
randno4=( )
you try to feed an ARRAY with a arithmetic expression with the wrong syntax.
See http://wiki.bash-hackers.org/syntax/arith_expr
And finally, like Etan Reisner said, You also use $randno3 in the t_twall assignment line which is undefined

Related

Updating (sequentially adding a value into) a variable within a for loop, in bash script

I am trying to update a variable within a for loop, sequentially adding to the variable, and then printing it to a series of file names.
Actually, I want to sequentially update a series of file, from a tmp file distTmp.RST to sequentially dist1.RST, dist2.RST, etc..
The original distTmp.RST contains a line called "WWW". I want to replace the string with values called 21.5 in dist1.RST, 22.5 in dist2.RST, 23.5 in dist3.RST, etc...
My code is as follows:
#!/bin/bash
wm=1
wM=70
wS=1
F=20.5
for W in {${wm}..${wM}..${wS}}; do
F=$(${F} + 1 | bc)
echo ${F}
sed "s/WWW/"${F}"/g" distTmp.RST > dist${W}.RST
done
echo ${F}
========
But I am getting error message as follows:
change.sh: line 13: 20.5 + 1 | bc: syntax error: invalid arithmetic operator (error token is ".5 + 1 | bc")
Kindly suggest me a solution to the same.
Kindly suggest me a solution to the same.
This might do what you wanted. Using a c-style for loop.
#!/usr/bin/env bash
wm=1
wM=70
wS=1
F=20.5
for ((w=wm;w<=wM;w+=wS)); do
f=$(bc <<< "$F + $w")
echo "$f"
sed "s/WWW/$f/g" distTmp.RST > "dist${w}.RST"
done
The error from your script might be because the order of expansion. brace expansion expansion happens before Variable does.
See Shell Expansion
Use
F=$(echo ${F} + 1 | bc)
instead of F=$((${F} + 1 | bc)). The doubled-up parentheses are what caused your error. Double parentheses weren't in the original code, but I get a different error saying 20.5: command not found with the original code, so I tried doubling the parentheses and get the error in the question. Apparently, floating point numbers aren't supported by $(()) arithmetic evaluation expressions in Bash.

How nest ancillary command in bash arithmetic command

I want to print the uptime for a jvm which is running on my machine. I can do that using jcmd. However I want to print it out in minutes. So, I tried the following:
bash-3.2$echo $(($(jcmd 785 VM.uptime)/60))
However this isn't working. I get the following error:
bash-3.2$ echo $(($(jcmd 785 VM.uptime)/60))
bash: 785:
1541.343 s/60: syntax error in expression (error token is ":
1541.343 s/60")
If I assign $(jcmd 785 VM.uptime) to a variable first and substitute that into the arithmetic expression, it still doesn't work. Any idea how I can get this to work?
Your output is not an integer, and has a character 's'. You should cut unnecessary part:
echo $(( $(jcmd 785 VM.uptime |sed 's/^\([[:digit:]]*\).*$/\1/')/60 ))
or
echo "scale=4;$(jcmd 785 VM.uptime |sed 's/ s//')/60" |bc
-- this will give you a float value.

Subtract 2 array values having floating point decimals

I'm reading a file with multiple columns, and dumping 2 columns of the file into into 2 different arrays. Now based on a condition, I need to get the difference between 2 values retrieved from the array. So my code looks like this -
if [ condition ]; then
VAL = (( ${local[$x]} - ${local[$y]} ))
fi
The thing is, while I'm able to echo and see both values ${local[$x]} and ${local[$y]}, the subtraction operation gives me a syntax error. I understand it's failing because the values currently held within the array involve floating point decimal values - like 3456712.126758, and the assignment throws errors with the decimal part. I understand arithmetic operations are not a strong point with the bash shell as floating point numbers are considered strings hence the issue.
Could you please help getting the right format please?
Should I do something like this
VAL= awk '{ print ${local[$x]} - ${local[$y]} }'
or
VAL=echo ${local[$x]} - ${local[$y]} | bc -l
I'm sure the syntax above is wrong, kindly help with the syntax, I need it assigned the subtracted result assigned to the field VAL.
Not only floating points, but also the spacing would lead to syntax errors. Bash variable assignments must have no spaces, as in val=x, and not val = x.
Uppercase variable names are reserved for environment variables, and it is recommended to use lowercase instead for your own variables. (Oh, and local is also a reserved word.)
Your assignment wouldn't work with proper spacing, either: the arithmetic expression
var=(( ${vals[$x]} - ${vals[$y]} )) # syntax error near unexpected token `('
is just evaluating its contents, but not returning anything. You could use the part after the = as a condition. To make it return something, you need arithmetic expansion (note the extra $):
var=$(( ${vals[$x]} - ${vals[$y]} )) # works for integers
^
In an arithmetic context, you don't even need to prepend $ to your variables:
var=$(( vals[x] - vals[y] ))
works just as well. Exception: in associative arrays, you still have to do it for indices:
$(( vals[$x] ))
And finally, as you noticed, this all doesn't work for floating point numbers. Instead of piping to bc, you can also use a here string and avoid spawning a subshell:
$ vals=(1.1 2.2)
$ x=0
$ y=1
$ echo $(( local[x] - local[y] )) # No '$' needed for variable expansion
bash: 1.1: syntax error: invalid arithmetic operator (error token is ".1") # But :(
$ bc -l <<< "local[x] - local[y]" # Requires '$' - these expand to nothing
0
$ bc -l <<< "${local[x]} - ${local[y]}" # Works!
-1.1
With awk:
awk -v a=${a} -v b=${b} 'BEGIN{print a - b}'
With bc:
echo "${a} - ${b}" | bc -l
See also other options here.

Bash Script Unexpected End of File - new coder

I'm new to bash, I'm just trying to pick in up in my free time. I'm writing a simple script that prints out the filename I supply as many times as there are characters in the filename, and then positive or negative based on the second argument. I'm getting an unexpected end of file error on this script, and I'm not sure why.
#!/bin/bash
FILENAME=$1
NUMBER=$2
COUNT=0;
STR=${#FILENAME}
while ($COUNT < $STR){
echo $FILENAME
$COUNT++
}
if ($NUMBER < 0)
echo "Negative"
if ($NUMBER > 0)
echo "Positive"
exit
I'm executing with
./script1.sh hello 2
and I'm expecting the output to be
hello
hello
hello
hello
hello
Positive
If anyone could shed some light as to what's going on with the error, that'd be great.
edit: forgot to add the second condition to add to the COUNT variable, and now I'm getting an error:
line 9: syntax error near unexpected token `{'
line 9: `while ($COUNT < $STR){'
Basically you are confusing Bash's syntax with some other language.
In Bash, if's syntax (if not using else) is if condition;then commands;fi. Your code does not have then and fi. Also, the condition should be (( $NUMBER > 0 )).
The syntax of while is while condition;do commands;done, and your code is also wrong.

"Simple" arithmetic

Why can't I do this simple arithmetic operation and store it in a variable in bash shell? I've been struggling with this and playing around with () and $ symbols but no luck.
read t
let r=$(5/9)*$($t-32)
I get a: let: r=*: syntax error: operand expected (error token is "*")
When you are using the let statement, you don't need the dollar-sign, but single-quote the expression instead to keep the shell preprocessor from messing with your operators. Note that bash does not seem to be able to handle numbers which aren't integers, so the (5/9) expression will always be zero. Try the second let statement.
read -p 'Temp in Fahrenheit (no decimals): ' t
# let r='(5/9)*(t-32)' -- this doesn't work
let r='5*(t-32)/9'
echo "Centigrade: $r"
Try that :
read -p 'Type integer temp (Fahrenheit) >>> ' int
echo "$(( 5 * ( int - 32 ) / 9 )) Celcius"

Resources