Reputation: 229
I'm a bash amateur reading up books and manuals for learning further. I came across following script in a book that calculates total size and shows the use of command substitution. I could not understand the parts that contain {totalsize:=0}
, {size:-0}
, {totalsize-unset}
. Could somebody please explain?
At first sight, it looked like an array but what do the operators :=
and :-
do here and totalsize
was the variable containing the values but when I echo ${totalsize-unset}
, it does return the sum of filesizes in PWD. Is -unset
some kind of built-in ?
$ while read perms links owner group size month day time file
> do
> printf "%10d %s\n" "$size" "$file"
> totalsize=$(( ${totalsize:=0} + ${size:-0} ))
> done < <(ls -l *)
$ echo ${totalsize-unset}
Upvotes: 4
Views: 3403
Reputation: 8162
(Ok let's be fair it's a contrived example to demonstrate Process Substitution with no warning about the security risks highlighted here. Unfortunate.)
In Bash, variables can be manipulated or expanded according to the syntax described here :
http://www.tldp.org/LDP/abs/html/parameter-substitution.html#PARAMSUBREF
The intention in the above script is simply to assign zero to totalsize if it does not have a value. totalsize will not have a value during the first iteration of the loop. zero will be used in the calculation instead.
There are a miriad of ways of achieving the same result. It would make more sense to use the du -h
command.
Run man du
first and understand what this command does (It estimates files space usage)
Upvotes: 4