简体   繁体   English

如何在bash shell中处理变量赋值?

[英]how variable assignment to be processed in bash shell?

I am confused about how variable assignment to be processed in shell. 我对如何在shell中处理变量赋值感到困惑。

For example: 例如:

  var=demo
  foo=$var

the $var will be expanded and the $foo will be "demo". $ var将被扩展,而$ foo将是“ demo”。

but if write as: 但是如果写为:

   count=0
   a_${count}=filename

the bash reports: a_0=filename: command not found bash报告: a_0 =文件名:找不到命令

From error message, we know a_${count} has expanded to a_0, so why variable assignment can't work? 从错误消息中,我们知道a _ $ {count}已扩展为a_0,那么为什么变量分配不能工作? I found also if write in another way: 我还发现是否以其他方式编写:

   count=0
   filename=a_${count}

everything will be ok, what difference between these?? 一切都会好的,这些之间有什么区别?

You cannot have an expression on left hand side of variable assignment. 变量赋值的左侧不能有表达式。

You can use declare instead: 您可以改为使用declare

declare a_${count}=filename

Then to verify: 然后验证:

echo "$a_0"
filename

The problem is that variable assignment happens before the expansion, if it is possible. 问题是如果可能的话,变量分配会在扩展之前发生。 If not, a_$count=filename is expanded and understood as a command to run. 如果不是,则将a_$count=filename扩展并理解为要运行的命令。 You can make it into a command to delay the assignment by using declare : 你可以把它变成一个命令使用延迟分配declare

declare a_$count=filename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM