Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

What is the difference that explains the different results of these commands?

  1. a=2 echo $a
  2. set a=2 echo $a
  3. a=2; echo $a
  4. set a=2; echo $a
share|improve this question

1 Answer 1

  1. a=2 echo $a

    Result: output a blank line

    Reason: Bash provides a subset of its variables (the environment) to every program you call with it (you can specify which with the export builtin). Prefixing a command with e.g. a=2 tells bash to add $a (with value 2) to the environment, but

    • only for that particular program, and
    • not to the set of variables used by bash itself.

    So, if echo were a program (it's actually a builtin), it would receive $a along with the other environment variables ... but echo doesn't care about environment variables - it just spits back the arguments you give it. Since $a isn't defined as a variable in bash itself, your command is equivalent to a bare echo, which emits a newline character, giving you a blank line.

  1. set a=2 echo $a

    Result: no output

    Reason: This isn't doing what you think it is - in fact, the echo command isn't called at all. When set is called without options, it sets the positional parameters to the arguments you give it, in order. You can see this with a couple of extra commands:

    $ set a=2 echo $a
    $ echo $1
    a=2
    $ echo $2
    echo
    

    ... and echo $3 gives a blank line, because you tried to set $3 to $a, which doesn't exist.

  1. a=2; echo $a

    Result: output 2 (at last!)

    Reason: This is the correct way to get what you want: you set the variable $a to 2, and then you called echo with $a as an argument.

  1. set a=2; echo $a

    Result:

    • If $a is already set to 2: output 2
    • If $a is not set: output a blank line

    Reason: Hopefully you can work this out for yourself, given the explanations above.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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