Home > front end >  What does the $ symbol mean in bash?
What does the $ symbol mean in bash?

Time:06-11

I am a bit confused with the $ symbol in bash. Why does the first line of the code work while the second line gives an error??

echo $(($1 * 2))
echo (($1 * 2))

Does the $ symbol work like a pointer?

And why does the first while loop not work while the second one does?

#giving error
n=1
while [$n -le 5]
do
    echo "Running $n time"
    ((n  ))
done

#Not giving error
n=1
while [ $n -le 5 ]
do
    echo "Running $n time"
    (( n   ))
done

CodePudding user response:

((...)) just evaluates and sets a return code.
$((...)) does that as well, but also replaces itself with the string representing the result.

n=1
while ((n<=5)); do echo "Running: $(( n   )) time(s)"; done
Running: 1 time(s)
Running: 2 time(s)
Running: 3 time(s)
Running: 4 time(s)
Running: 5 time(s)

Your error was here -

while [$n -le 5]

Spaces (or other similarly clarifying metacharacters) are required around the [ operator, but not inside ((...)) where the more limited syntax is less ambiguous in general. Paste your code in at https://www.shellcheck.net/ and it will show you things like this in seconds, with explanations.

c.f. this page for more info.

  • Related