script recursion

Can someone please explain me why the following script calls it self recursively:

#!/bin/bash
echo Called
$0

while this not:

#!/bin/bash
echo Called
$($0)

Thanks

$0 is a built-in shell variable, meaning the 'first' word, that is, command name, and will include the full pathname. Likewise, the first parameter $1 is actually the second word, and $2, the third word, etc...

Putting the $variable inside $($variable) is like typing

$(/$HOME/bin/scriptname)

at the command line where nothing will happen.

I can see that, my question is why :slight_smile:

Sorry, I thought maybe you didn't understand $0.

Honestly, I don't know why, it most likely has to do with variable expansion, or pattern matching, just type

$(/bin/bash)

and nothing happens. Maybe someone else knows WHY?

The second case ($($0)) is using command substitution. The result of this would be to replace the command with the standard output of the command substitution (in this case itself ($0)), and so it would call itself.

OK. It's very late, and I'm having trouble wording that, so search for "Command Substitution" in the man page :smiley:

1 Like

Thank you scottn! Here's the relevant part..

Bash performs the expansion by executing command and replacing the command substitution with the standard output of the command, with any trailing newlines deleted.

Yes, I should have just quoted the man page instead of babbling on like I invented it :smiley: