Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can substring variable expansion reference a variable without a dollar sign?

In bash, to get the first 4 characters of a variable, you can do:

variable='this is a variable'
echo ${variable:0:4}

Instead of hard-coding the length, you can reference a variable like this:

length=4
echo ${variable:0:$length}

However, it seems that you can leave off the $ off length as well:

echo ${variable:0:length}

It does not make sense to me that you should be able to do this because I always thought that to use/evaluate a variable, you have to prefix it with $.

In other languages, I would expect the text after each : to be a number or an expression that evaluates to a number. And in bash, length wouldn't evaluate to anything, but $length would.

This is confusing. Could someone help me understand what is going on here?

like image 666
Niko Bellic Avatar asked Jun 29 '26 23:06

Niko Bellic


1 Answers

In general is correct to use the "$" symbol to expand a variable, but in some cases the bash auto-expands variable. For example in context like arithmetics or indirect expansion (see Shell expansion to more detailed information). However your case is a simple arithmetic context expansion.

like image 149
Zig Razor Avatar answered Jul 01 '26 17:07

Zig Razor