'Variable $x$n in arithmetic expansion
I come across this tutorial example, especial the line sum=$(($sum+$x$n)). What does $x$n mean in particular? I suppose $x is referenced but not assigned (undeclared/unset variable), isn't it?
https://linuxhint.com/bash_eval_command/
evaltest3.sh
#!/bin/bash
# Initialize the variable $sum with the value 0
sum=0
# Declare a for loop that will iterate for 4 times
for n in {1..4}
do
# Create four variables using eval command
eval x$n=$n
# Add the values of the variable with $sum
sum=$(($sum+$x$n))
done
# Assign `echo` command with string into a variable
command="echo 'The result of the sum='"
# `eval` command print the sum value using variables
eval $command $sum
Solution 1:[1]
(Does not directly answer your question, but offers an alternative)
Since bash arithmetic allows us to provide variables "without using the parameter expansion syntax" [Ref] (i.e. without the $), we can write
for n in {1..4}; do ((sum += n)); done
The advantage is that bash handles empty or unset variables as the number zero.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
