0

Could someone help me with Bash logic?

I don't think it's my environment, I think I'm having trouble getting my head around some simple logic. Can someone explain why/how the following happens, and if there's a way to alter the outcome?

number=6
echo $number
6
test=$number
echo $test
6

So far so good

number=11
echo $test
6
test=$number
echo $test
11

I have to issue test=$number again for 11 to be displayed. Obviously this is by design, is there a way to generate 11 as the response without issuing test=$number again?

  • namerefs as described in https://unix.stackexchange.com/a/413479/70524 seems to be what you're looking for – muru Mar 28 '24 at 07:41

1 Answers1

1

This isn't C/C++/any other language with pointers. If you do test=$number, you assign the value of the variable number to the variable test, not the address. So changing number later won't affect the test variable at all.

Also, I would recommend you to not name your variable test since it is a built-in command. You can - nothing will break - but its not fancy^^

Bog
  • 989
  • 1
    variables don't share the same namespace with commands, though, you can write test "$test" without any conflicts – ilkkachu Mar 28 '24 at 07:56
  • You are right but isn't this still bad practice? – Bog Mar 28 '24 at 07:59
  • @ilkkachu Well, there's nothing stopping you from naming variables like standard utilities or shell keywords, but it certainly does not help with reading the code. – Kusalananda Mar 28 '24 at 08:14
  • @Kusalananda, no jaa, there's things like "enable", "time", "command" and "umask" that are rather generic or work as rather obvious nouns. (Of course that test "$test" above is rather obfuscated.) – ilkkachu Mar 28 '24 at 08:40