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
  • 5
  • 16
Yan Zhuang
  • 101
  • 2
  • See [$VAR vs ${VAR} and to quote or not to quote](https://unix.stackexchange.com/questions/4899/var-vs-var-and-to-quote-or-not-to-quote) – steeldriver Nov 25 '20 at 12:47

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
  • 133,243
  • 15
  • 236
  • 397
icarus
  • 17,420
  • 1
  • 37
  • 54
  • `$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