3

I've been wondering what's the difference between the two:

  • CAROOT='certificates'; echo $CAROOT - prints the value, uses ; as separator between two commands
  • CAROOT='certificates' echo $CAROOT - prints empty value.

I wonder why the former command works but the latter didn't?

1 Answers1

4

The following command line and its output can help explain how it works.

$ LANG=C bash -c 'echo LANG=$LANG'; echo LANG=$LANG
LANG=C
LANG=sv_SE.UTF-8

LANG=C with only a space works only on the following command, after that the old LANG setting is used again.

But why does it print an empty value in your second case? I would explain it like this: The variable will be expanded by the shell directly. This is different from the case with bash -c 'echo LANG=$LANG', where the variable is protected [by the quotes] at first, and will be expanded later, when the previous variable set command has already been processed.


The method with only a space, no semicolon is often used, when you want to change language temporarily, as in the following example where the heading is changed to the standard language (English).

$ df -h
Filsystem      Storlek Använt Ledigt Anv% Monterat på
udev               16G      0    16G   0% /dev
tmpfs             3,2G   1,6M   3,2G   1% /run
/dev/sda5          88G    32G    52G  39% /
tmpfs              16G      0    16G   0% /dev/shm
tmpfs             5,0M   4,0K   5,0M   1% /run/lock
tmpfs              16G      0    16G   0% /sys/fs/cgroup
/dev/sdb7         3,5T   998G   2,4T  30% /media/multimed-2
tmpfs             3,2G    20K   3,2G   1% /run/user/1000

$ LANG=C df -h Filesystem Size Used Avail Use% Mounted on udev 16G 0 16G 0% /dev tmpfs 3,2G 1,6M 3,2G 1% /run /dev/sda5 88G 32G 52G 39% / tmpfs 16G 0 16G 0% /dev/shm tmpfs 5,0M 4,0K 5,0M 1% /run/lock tmpfs 16G 0 16G 0% /sys/fs/cgroup /dev/sdb7 3,5T 998G 2,4T 30% /media/multimed-2 tmpfs 3,2G 20K 3,2G 1% /run/user/1000

sudodus
  • 47,864
  • 1
    Setting a variable with only space before a command sets that variable to be only available in that command's scope/environment check var='123' printenv var … however with the var='123' echo “$var”, $var gets expanded by the running shell before the echo command is run and even before var itself is set … hence the empty string … i.e. expansion happens first … the ; nests procedures in the order they will be executed and sets var in the environment of the running shell before the next procedure after ; including the expansion of $var happens … hence its value is printed. – Raffa Aug 01 '22 at 18:58
  • Yes, @Raffa, your explanation is good :-) – sudodus Aug 01 '22 at 19:03
  • +1 and :-) … Couldn’t include these in the first comment due to darn character limit. – Raffa Aug 01 '22 at 19:05