可变$ x $ n算术扩展

发布于 2025-01-22 17:21:31 字数 740 浏览 0 评论 0原文

我遇到了这个教程示例,尤其是行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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

☆獨立☆ 2025-01-29 17:21:31

(不是直接回答您的问题,而是提供替代方案)

,因为Bash Arithmetic允许我们提供变量“不使用参数扩展语法” [ ref ](即没有$),我们可以写出

for n in {1..4}; do ((sum += n)); done

优势是bash bash and bash and bash and bash and bash and bash andley and bash and bash andlen offeres数量零。

(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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文