我从脚本用户获取变量的名称作为第一个参数,并将所述变量的值回显给控制台:
#!/bin/bash variablename=$1 echo "The value of $variablename is: " ${!variablename}
这很棒!
我无法工作的是,如果我想将该变量更改为用户的第二个参数的值.语法错误的示例是:
#!/bin/bash variablename=$1 echo "The value of $variablename is: " ${!variablename} echo "I will now try to change the value into $2." (!variablename}=$2 # The above line generates: {!variablename}=2: command not found
换句话说:如果可能,我如何从用户获取变量名称并读取(已经解决)并写入所述变量?
在请求帮助后几分钟我突然闪过,我想我有一个解决方案:
#!/bin/bash variablename=$1 echo "The value of $variablename is: " ${!variablename} echo "I will now try to change the value into $2." eval "$variablename=$2" echo "Success! $variablename now has the value ${!variablename}!"
有用.有没有更好的办法?