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/
#!/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
(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 ] (ie 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.