简体   繁体   English

在Shell脚本中为for循环中的变量分配值

[英]Assigning value to a variable in for loop in shell scripting

I am trying to split letters from a word and print them in new line using the following method. 我正在尝试从单词中拆分字母,然后使用以下方法将它们打印在新行中。 But I am not able to assign values to the variable. 但是我不能给变量赋值。 Correct me if I am missing any fundamental rule here. 如果我在这里缺少任何基本规则,请纠正我。

stringOneLength=$(echo `expr length $1`)
echo $stringOneLength
stringTwoLength=$(echo `expr length $2`)

echo $stringTwoLength


for ((i=1; i<=$stringTwoLength; i++)) ;
do
    x$i=$(echo "$1" | sed 's/\(.\{1\}\)/\1 /g' | sed 's/\(.\{1\}\)/\1 /g' |awk '{print $i}')

    echo x$i
done

Getting following error: 出现以下错误:

sh FileName one two
3
3
samp: line 13: x1=o: command not found
x1
samp: line 13: x2=o: command not found
x2
samp: line 13: x3=o: command not found
x3

What is wrong with my approach and how can I fix my variable assignment? 我的方法有什么问题,如何解决变量分配问题?

It looks like you're trying to dynamically create variable names using $i . 看来您正在尝试使用$i动态创建变量名。 Firstly, I would recommend against this if possible - it would be better to use an array if your shell supports it. 首先,如果可能,我建议不要这样做-如果您的外壳支持数组,则最好使用数组。 However, it can be done using eval : 但是,可以使用eval来完成:

eval x$i=$( ... )

Using eval , the $i is expanded before the assignment takes place. 使用eval ,将在分配发生之前扩展$i

Using bash, there's also declare , which you can use instead of eval . 使用bash,还可以进行declare ,您可以使用它代替eval It deservedly has a better reputation than eval as it is safer. 理所应当的声誉比eval更好,因为它更安全。 However, if you're using bash, you can (and should) use an array instead: 但是,如果您使用的是bash,则可以(并且应该)使用数组:

x=() # before the loop
x[i]=$( ... )

It's also worth mentioning that if you don't actually need to store each value separately (ie you don't plan on using them later on), you can just remove the $i entirely and do a simple assignment in the loop: 还值得一提的是,如果您实际上不需要分别存储每个值(即以后不打算使用它们),则可以完全删除$i并在循环中进行简单的赋值:

x=$( ... )

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

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