JONAS402 JONAS402 - 1 month ago 4
Bash Question

simple shell script to add 2 variables

Hi I'm trying to get this simple she'll script to work but I keep encountering the error:

bday.sh[9]: 2015-1987: not found

bday.sh[9]: yearb=: not found

Here is my code so far

echo "what year is it?"
read "year"
echo "what year were you born?"
read "byear"
"yearb"="$( ( "$year"-"$byear" ) )"
echo "$yearb"


Thanks in advance guys!

Answer

Kudos for quoting, but it really just applies to parameter expansion, like in echo "$yearb".

Unexpanded variable names (without a preceding $) don't need quoting, and sometimes can't have it:

yearb=$(( year - byear ))

Also, the syntax $(( (arithmetic expansion) is its own syntactic element so no spaces are allowed.

$( (..) ) is instead $(..) (command expansion) with a nested (..) (subshell).

Here's a complete example:

$ cat script 
echo "what year is it?"
read "year"
echo "what year were you born?"
read "byear"
yearb=$(( $year - $byear ))
echo "$yearb"

$ bash script
what year is it?
2015
what year were you born?
1970
45