bashvariable-expansion

Why can't I set a variable and then echo it right away in bash


EDIT: The point of this question is to make it possible to Google this. While the flagged duplicate question has the same answer, it's in some sense not the same question, because that question is specifically about using env.


In bash, why does

A=1 echo $A

produce a blank line instead of

1

as expected?


Solution

  • Answer:

    Bash evaluates $A prior to running A=1.

    Demonstration:

    $ export A=1
    $ A=2 echo $A
    1
    

    One workaround:

    $ cat > echoa.sh
    #!/bin/bash
    
    echo $A
    ^D
    $ chmod +x echoa.sh
    $ A=5 ./echoa.sh
    5