Jayesh Bhoi
Jayesh Bhoi

Reputation: 25915

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

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

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

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

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

which also cause error.

Upvotes: 2

Views: 14873

Answers (3)

Малъ Скрылевъ
Малъ Скрылевъ

Reputation: 16514

Rename the variable name as follows:

SM_Read_only="Yes"
SM_write_only="No"

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

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

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

Upvotes: 9

n0p
n0p

Reputation: 3496

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

SM_Read_only

Or

SM_ReadOnly

Upvotes: 1

Barmar
Barmar

Reputation: 782498

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

Upvotes: 5

Related Questions