1

I came across two Unix scripts in my textbook. In one of them they implemented a=$b (in the form of max=$a) and in the other a=b (in the form of number=num).

Question

Are these the same thing or is there a difference?

NOTE: I'm new to Unix scripting so please bare with me.

  • 2
    Could you provide us an example of the script please? – tachomi Nov 24 '14 at 17:35
  • I am reasonably sure the textbook you are reading has an explanation of each. – mkc Nov 24 '14 at 17:36
  • 1
    The textbook I have is crap. It has lots of mistakes, so I tend to verify on the internet. – Arjunsinh Jadeja Nov 24 '14 at 17:38
  • @Ketan It actually sounds like both cases intended to use the variable assignment (a=$b), and the latter case had a typo. But a code snippet would help clarify. – augurar Nov 24 '14 at 19:36
6
$ a=b
$ printf $a
b
$ b=hello
$ a=$b  
$ printf $b
hello

Basically a=b makes a variable called a of which value is a literal b. a=$b makes a variable called a with the same value as an already existing variable called b.

  • 1
    I'd put b assignment to "hello" as the first line – Olivier Dulac Nov 25 '14 at 23:32
3

In case of, a=$b you are assigning the value of the variable b to a. While in case of a=b you are assigning a the value of the literal string "b"

E.g. b=10, Now suppose you want to assign a the same value as b. You can do either of the following:

a=$b

or,

a=10
  • "While in case of a=b you are assigning a the value b" So in case after using a=b we change the value of b then will a get automatically updated? – Arjunsinh Jadeja Nov 24 '14 at 17:42
  • It was badly phrased; I have tweaked the answer to be more clear. – DopeGhoti Nov 24 '14 at 18:09
2

You can ask bash for help in answering these questions too, using set -x. This flag tells bash to display the command and its expanded arguments before running it:

First, some setup:

$ a=some-value
$ b=some-other-value
$ set -x

Now let's see how the shell interprets these commands:

$ a=b
+ a=b

The value of the variable a is being set to the literal string "b".

Now let's try $b:

$ a=$b
+ a=some-other-value

Here we tell the shell to evaluate $b and insert the value of b into the command.

This shows some of the value of the shell -- it interprets variables and wildcards instead of making individual commands do the work. For example, ls doesn't have to know how to interpret "*.txt" because the shell does the work before ls is started:

$ ls *.txt
+ ls a.txt b.txt c.txt
a.txt  b.txt  c.txt

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.