简体   繁体   中英

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?

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 .)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM