bash 如何在linux bash脚本中用“-”字符(破折号)声明变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21525424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:26:10  来源:igfitidea点击:

how to declare variable name with "-" char (dash ) in linux bash script

linuxbash

提问by Jayesh Bhoi

I wrote simple script as follow

我写了简单的脚本如下

#!/bin/bash

auth_type=""

SM_Read-only="Yes"
SM_write-only="No"

echo -e  ${SM_Read-only}
echo -e  ${SM_Write-only}

if [ "${SM_Read-only}" == "Yes" ] && [ "${SM_Write-only}" == "Yes" ] 
then
    auth_type="Read Write"
else
    auth_type="Read"
fi

echo -e $auth_type

And when i execute it i got following output with errors.

当我执行它时,我得到以下输出错误。

./script.bash: line 5: SM_Read-only=Yes: command not found
./script.bash: line 6: SM_write-only=No: command not found
only
only
Read

Any one know correct way to declare the variable with "-" (dash)?

有人知道用“-”(破折号)声明变量的正确方法吗?

EDIT:

编辑:

have getting response from c code and evaluate the variables for example

例如从 c 代码得到响应并评估变量

RESP=`getValue SM_ Read-only ,Write-only 2>${ERR_DEV}`
RC=$?
eval "$RESP"

from above scripts code my c binary getValueknow that script want Read-onlyand Write-onlyand return value to script.So during eval $RESPin cause error and in my script i access variable by

从上面的脚本代码我的 c 二进制文件getValue知道脚本想要Read-onlyWrite-only返回值到脚本。所以eval $RESP在导致错误和我的脚本中我访问变量

echo -e  ${SM_Read-only}
echo -e  ${SM_Write-only}

which also cause error.

这也会导致错误。

回答by Малъ Скрылевъ

Rename the variable name as follows:

重命名变量名称如下:

SM_Read_only="Yes"
SM_write_only="No"

Please, don't use -minus sign in variable names in bash, please refer to the answer, on how to set the proper variable name in bash.

请不要-bash中的变量名中使用减号,请参阅答案,了解如何在bash 中设置正确的变量名。

However if you generate the code, based on others output, you can simply process their output with sed:

但是,如果您根据其他人的输出生成代码,您可以简单地使用sed处理他们的输出:

RESP=$(getValue SM_ Read-rule,Write-rule 2>${ERR_DEV}|sed "s/-/_/")
RC=$?
eval "$RESP"

回答by Barmar

-is not allowed in shell variable names. Only letters, numbers, and underscore, and the first character must be a letter or underscore.

-不允许在 shell 变量名中出现。只有字母、数字和下划线,并且第一个字符必须是字母或下划线。

回答by Coconop

I think you cant have a dash in your variables names, only letters, digits and "_" Try:

我认为你的变量名不能有破折号,只有字母、数字和“_”试试:

SM_Read_only

SM_只读

Or

或者

SM_ReadOnly

SM_只读