0

I am a beginner in Unix commands as I am currently studying how to write scripts. However, I can't understand how to actually access a variable.

Suppose I have a variable called name ($name), I see that sometimes people access it by using directly $name, while others use ${name} or even "$name". So this is very confusing, I am not sure what is the difference, as this is totally different from what I have learned in other programming languages.

Also, when I try to assign a string to a variable, do I write $name="happy", $name=happy, "$name=happy" or let "$name=happy".

mnille
  • 529
Yan Zhuang
  • 101
  • 2

1 Answers1

6

There is no difference between $fred and ${fred}. The use of {} is needed if you need to say where the variable name ends. For example echo ${end}ing outputs the value of the end variable followed by the letters ing whilst echo $ending outputs the value of the ending variable.

The use of double quotes is to stop word splitting. As a rule of thumb every time you use a variable it should be in double quotes unless you know you want the result broken into words or you know that the values are ones which will never be split* (see also When is double-quoting necessary?).

As far as your examples for assigning are concerned, you probably don't want the $ signs in any of them.

  1. name="happy" - This is the thing you should use
  2. name=happy - This works because "happy" is a single word, fine to use interactively but probably should be avoided in scripts
  3. "name=happy" - Try to run a command with an unusual name of name=happy, almost certainly wrong.
  4. let "name=happy" - runs a command called let which has its own rules, usually used for arithmetic in bash.

Footnote

* This is an over simplification but easy to remember. See the specification for details of how commands are processed.

ilkkachu
  • 138,973
icarus
  • 17,920
  • $name=happy as the question had it, would expand $name and then try to run foo=happy as a command, so it won't work as an assignment. – ilkkachu Nov 25 '20 at 09:38
  • 1
    As a general rule, you use $ to get the value of a variable, but not when setting it (as in var="value" or read var) or when getting/setting its properties (export var or declare -p var). – Gordon Davisson Nov 25 '20 at 09:46