bash:使用以下代码执行“ for循环”后,显示变量的空值

时间:2019-03-21 00:26:10

标签: braces

从“ for循环”创建变量,然后将字符串关联到 it.New值显示为null。
预期产量: colname1 = hash(id)as id
colname2 = hash(cust)作为客户

实际输出:
colname1 =''
colname2 =''

#!/bin/bash
hcd1="hash("           # string to be added
hcd2=")as "            #string to be added 
dmk=id,cust
IFS=" ,"
i=0
for val in ${dmk}
do
  i=$((++i))
  eval var${i}="${val}"
done
for ((j=1;j<=i;++j))
do
  name="var${j}"
  colname="col${j}"
  echo ${colname} = "$hcd1${!name}$hcd2 ${!name}"
done
echo "$colname1    $colname2 "

1 个答案:

答案 0 :(得分:0)

一些注意事项:

  • $ {dmk}不扩展逗号。您的循环将是:一个元素:'id,cust'
  • 您不需要大括号来插入变量$ {dmk}与$ dmk相同
  • $ {!name}似乎无效。可能您是说$ name

进行了一些修正

#!/bin/bash
hcd1="hash("           # string to be added
hcd2=")as "            #string to be added 
dmk="id cust"
#IFS=" ,"
i=0
for val in $dmk
do
  i=$((++i))
  eval var$i="$val"
  #echo  var$i="$val"
done
for ((j=1;j<=i;++j))
do
  eval name='$'"var$j"
  colname="col$j"
  echo $colname = "$hcd1$name$hcd2 $name"
done

输出

col1 = hash(id)as  id
col2 = hash(cust)as  cust