2

Are there any rules for unix/linux shell variable naming?

For example, like the common rules for Java variable naming.

2

1 Answer 1

3

You have to be very careful not to use any UNIX command as a variable. It will mess the code and produce unexpected results. Also, keep in mind the reserved words (if, else, elif, do, done...) and that uppercase variables are reserved for system use.

From Rules for Naming variable name:

Variable name must begin with alphanumeric alpha character or underscore character (_), followed by one or more alphanumeric or underscore characters. Valid shell variable examples

Or as seen in The Open Group Base Specifications Issue 7:

In the shell command language, a word consisting solely of underscores, digits, and alphabetics from the portable character set. The first character of a name is not a digit.

Sign up to request clarification or add additional context in comments.

7 Comments

thanks for your response, i understand shell has its mandatory requirement about variable naming, i want to know do we have any recommendation about variable naming, for example: VAR_NAME or varName or var_name, which one is the best to use?
Shells expect variables to be preceded by $, so having a variable called $ls or $done (although initialised with ls=1 or done=1) doesn't seem to cause problems - even if it looks confusing. Can you give an example where it doesn't work?
No, you can write it the way you prefer. The only suggestion I can give you is to be constant on your decision, writing all the variables the same way: if you choose var_name, do always var_name and do not create any VarName or varName. It will help reading the code. But it is an esthetic decision, shell will not complain.
@BinaryZebra very good point. Thanks for the correction and the link. Updated!
This lacks an important detail from stackoverflow.com/questions/673055/…
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.