gpt4 book ai didi

linux - Bash for 循环可变数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:56:01 24 4
gpt4 key购买 nike

我的情况是我有大量编号的变量。如果条件匹配,我想评估每个变量并将变量设置为特定字符串。

#!/bin/bash
var1=""
var2="1233123213"
var3="22332323222324242"
var4=""
var5=""

for i in 1 2 3 4 5
do
if [ -z "$var{$}i" ]
then
var{$}i="None"
fi
echo "var{$}i \r"
done

但问题是当我运行我得到的脚本时。

{1} \r
{2} \r
{3} \r
{4} \r
{5} \r

我该如何解决这个问题。

最佳答案

Use indirect variable expansion in bash with syntax {!var}.

man bash 页面,

If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exclamation point must immediately follow the left brace in order to introduce indirection.

将您的代码修改为如下所示,

for i in 1 2 3 4 5
do
var="var$i"
[ -z "${!var}" ] && declare "var$i"="none"
done

printf "var1=%s\n" "$var1"
printf "var2=%s\n" "$var2"
printf "var3=%s\n" "$var3"
printf "var4=%s\n" "$var4"
printf "var5=%s\n" "$var5"

在这种情况下,语法 "${!var}" 评估字符串 var 中的变量值,即 var1var2, var3... 和 declare 语法在运行时设置变量值,仅针对那些为空的变量。现在打印这些变量产生,

var1=none
var2=1233123213
var3=22332323222324242
var4=none
var5=none

关于linux - Bash for 循环可变数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42066402/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com