2

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

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

codeforester
  • 39,467
  • 16
  • 112
  • 140
Emre He
  • 497
  • 11
  • 23
  • and also for the shell function name? – Emre He Feb 27 '13 at 09:31
  • Possible duplicate of [Shell script variable naming convention](http://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization/42290320#42290320) – codeforester Feb 18 '17 at 06:46

1 Answers1

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.

fedorqui
  • 275,237
  • 103
  • 548
  • 598
  • 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? – Emre He Feb 27 '13 at 09:30
  • 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? – Dougall Feb 27 '13 at 09:31
  • 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. – fedorqui Feb 27 '13 at 09:33
  • @BinaryZebra very good point. Thanks for the correction and the link. Updated! – fedorqui Nov 19 '15 at 10:25
  • This lacks an important detail from https://stackoverflow.com/questions/673055/correct-bash-and-shell-script-variable-capitalization – tripleee Jan 17 '19 at 05:32
  • @tripleee I am a bit out these days. Do you mean having them lowercase? – fedorqui Jan 17 '19 at 08:35
  • Yes, the fact that uppercase variables are reserved for system use. – tripleee Jan 17 '19 at 08:40