[英]Variable $x$n in arithmetic expansion
我遇到了这个教程示例,特别是行sum=$(($sum+$x$n))
。 $x$n
是什么意思? 我想 $x 被引用但未分配(未声明/未设置变量),不是吗?
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
(不直接回答你的问题,但提供了一个替代方案)
由于 bash 算术允许我们“不使用参数扩展语法”[ Ref ](即没有$
)提供变量,我们可以写
for n in {1..4}; do ((sum += n)); done
优点是 bash 将空变量或未设置变量处理为数字零。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.