Shell var+;=添加字符串而不是总和

Shell var+;=添加字符串而不是总和,shell,scripting,Shell,Scripting,我必须制作一个脚本,使所有进程的PID总和大于20。这是可行的,但有些地方出了问题。我知道这很简单,但我不懂逻辑 例如,我有两个进程,“1504”和“1405”。我的总和是15041405。如何重新写入sum+=${proc[$I]}以生成实际的sum,而不是字符串附加 proc=( $(ps | cut -d ' ' -f1) ) nr=$(ps | cut -d ' ' -f1 | wc -l) sum=0 for (( i=0 ; i<=nr ; i++)); do [[ $

我必须制作一个脚本,使所有进程的PID总和大于20。这是可行的,但有些地方出了问题。我知道这很简单,但我不懂逻辑

例如,我有两个进程,“1504”和“1405”。我的总和是15041405。如何重新写入sum+=${proc[$I]}以生成实际的sum,而不是字符串附加

proc=( $(ps | cut -d ' ' -f1) )

nr=$(ps | cut -d ' ' -f1 | wc -l)

sum=0

for (( i=0 ; i<=nr ; i++)); do

[[ ${proc[$i]} -gt 20 ]] && sum+=${proc[$i]}


done


echo $sum
proc=($(ps | cut-d'-f1))
nr=$(ps |切割-d'-f1 | wc-l)
总和=0

对于((i=0;i使用数学上下文。在POSIX sh中:

sum=$(( sum + val ))
…或者,也是有效的POSIX:

: "$(( sum += val ))"
…或者,在bash中:

(( sum += val ))
您还可以在数学上下文中使用更易于阅读的比较操作,而不是在非数学测试上下文中使用-gt。在bash中:

(( ${proc[$i]} >= 20 )) && (( sum += ${proc[$i]} ))
…或在POSIX shell中(它不支持数组,因此无法准确地复制示例代码):

…或者,要在glob引擎上投入更多精力:

# avoid inflating the result with non-matching globs
shopt -s nullglob

# define a function to avoid overwriting the global "$@" array
count_procs() {
  set -- /proc/[3-9][0-9] /proc/[0-9][0-9][0-9]*
  echo "$#"
}

# ...used as follows:
count_procs

在shell中,所有内容都被视为字符串,除非您特意将其转换为其他形式(在数学上下文中,或者利用bash中几乎从未使用过的对声明整数变量的支持)--因此,除非你特意去做,否则
foo+=bar
是字符串连接就不奇怪了。顺便问一下--你到底为什么要做
ps | cut | wc-l
?行的内容被扔掉了,
cut
增加了什么值?就个人而言,我根本不会使用ps,我会这样做请仔细检查
/proc/[0-9]*
…我也不确定对PID求和(而不是计数)得到的值,但这是另一个问题。
count=0
for pid_file in /proc/[0-9]*; do
  pid=${pid_file##*/}
  (( pid > 20 )) && (( count++ ))
done
printf '%s\n' "$count"
# avoid inflating the result with non-matching globs
shopt -s nullglob

# define a function to avoid overwriting the global "$@" array
count_procs() {
  set -- /proc/[3-9][0-9] /proc/[0-9][0-9][0-9]*
  echo "$#"
}

# ...used as follows:
count_procs