简体   繁体   English

Bash脚本:变量未正确递增

[英]Bash scripting: variable is not incrementing correctly

I am writing a bash script to loop through all the directories and rename the directory to the value of the array, but it seems my (i th) value is not incrementing correctly and it also says "(i th) command not found" when I run my bash script. 我正在编写一个bash脚本以遍历所有目录并将目录重命名为数组的值,但似乎我的(i th)值未正确递增,并且在出现以下情况时还会显示“未找到(i th)命令”我运行我的bash脚本。

Here is my code: I replaced the values inside Unix with place holder values. 这是我的代码:我用占位符值替换了Unix内部的值。

#!/bin/bash 

declare -a Unix=(value1 value2 value3 .... );

i = 0
for d in */; do 
    echo ${Unix[$i]}
    #mv $d ${Unix[$i]}
    (($i+1))
done

You are doing two things wrong. 您做错了两件事。 Firstly , to answer your problem, 首先,要回答您的问题,

(($i+1))

should be 应该

(($i+=1)) 

also, you should remove the spaces in the line 另外,您应该删除行中的空格

i = 0 

so it looks like 所以看起来

i=0

Firstly, you might want to quote your directory names in the mv command, or you get into trouble with names containing spaces: 首先,您可能想在mv命令中引用目录名称,否则您将遇到包含空格的名称的麻烦:

mv "$d" "${Unix[i]}"

As you see, it's not necessary to prepend the i in the index with $ , as [] is an "arithmetic context" here and expands variable names. 如您所见,没有必要在索引中的i前面加上$ ,因为[]在此处是“算术上下文”并扩展了变量名。

Secondly, your increment does nothing: you just add 1 to i and throw the result away. 其次,您的增量没有任何作用:您只需将i加1并丢弃结果即可。 You can use the increment operator instead: 您可以改用递增运算符:

(( ++i ))

Again, the $ is not needed. 同样,不需要$

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

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