0

for command substitution in bash, we do this

hello=$(ls -la)  
echo "$hello"

but when i do the same for below command,it fails,it says RANDOM not found

hell=$(RANDOM)
echo "$hell"

I can get over it ,by using arithematic expansion..

hell=$((RANDOM))
echo "$hell"

Any idea why below doesn't work...as per my understanding, RANDOM is also a command and i should have gotten number echoed

hell=$(RANDOM)
echo "$hell"
1
  • RANDOM directly fails on bash,but echo $RANDOM works Commented Apr 17, 2022 at 17:02

1 Answer 1

4

RANDOM isn't a command, it's a variable. Just one set by the shell and a bit of a special one:

RANDOM Each time this parameter(*) is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If RANDOM is unset, it loses its special properties, even if it is subsequently reset.

Something like echo "$RANDOM" is exactly how you'd use any variable, like the more "normal", HOME and BASH_VERSION. Of course ${RANDOM}, with braces and not regular parentheses works too.

Being able to use it in an arithmetic expansion without the $ is also a feature of the arithmetic context, and works for any variable:

Within an expression, shell variables may also be referenced by name without using the parameter expansion syntax.

(e.g. x=4; echo "$((x*x))" prints 16)

(* You can ignore the variable vs. parameter distinction here.)

2
  • Thank you for the clarification ,still learning bash. It's very complicated compared to modern languages Commented Apr 17, 2022 at 17:13
  • 2
    @TheGameiswar, being a rather direct descendant of a 40+ year old shell comes with some, ah, quirks. Plus the terseness, one really has to be careful with the special characters, $(foo), $((foo)) and ${foo} are all somewhat different.
    – ilkkachu
    Commented Apr 17, 2022 at 17:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .