Ren
Ren

Reputation: 2946

What does the '${var// /+}' mean in shell script?

I have never seen the following shell script syntax:

cpu_now=($(head -n 1 /proc/stat))
cpu_sum="${cpu_now[@]:1}"
cpu_sum=$((${cpu_sum// /+}))

Can anyone explain what the ${cpu_sum// /+} mean here?

Upvotes: 3

Views: 93

Answers (2)

anubhava
anubhava

Reputation: 785481

cpu_sum=$((${cpu_sum// /+}))

It is actually 2 step operation:

  1. First all the spaces are being replaced by + in ${cpu_sum// /+}
  2. Then using $((...)) arithmetic addition is being performed for adding all the numbers in $cpu_sum variable to get you aggregate sum.

Example:

# sample value of cpu_sum
cpu_sum="3222 0 7526 168868219 1025 1 357 0 0 0"

# all spaced replaced by +
echo ${cpu_sum// /+}
3222+0+7526+168868219+1025+1+357+0+0+0

# summing up al the values and getting aggregate total
echo $((${cpu_sum// /+}))
168880350

Upvotes: 4

ruakh
ruakh

Reputation: 183456

It means the same as $cpu_sum, but with all occurrences of  (a space) being replaced by +. (See §3.5.3 "Shell Parameter Expansion" in the Bash Reference Manual.)

Upvotes: 6

Related Questions