Bash: assigning output of command substitution to an integer variable

bash

Solution

Still `bash`-specific, but a cleaner way of getting a space-free integer might be:

job_pids=( $(jobs -p) )
n_jobs=${#job_pids[@]}

A POSIX-compliant version:

n_jobs=$( jobs -p | awk '{print NR}' )

(The `-p` isn't necessary, but you really don't need anything more than a unique line per job to feed to `awk`, so may as well make the lines as brief as possible.)

Problem

In Bash, I need an integer variable, like this: ``` declare -i n_jobs ``` to be assigned as a value the number of current background jobs: ``` jobs | wc -l ``` If I assign it as so: ``` n_jobs=$(jobs | wc -l) ``` is seems like a working integer, e.g.: ``` echo $((++n_jobs)) ``` but... printing it (without running the increment above) reminds me that it contains blanks: ``` $ echo "$n_jobs" $ <space><space><space><space><space>4 ``` so I resort to this construct: ``` n_jobs=$(( $(jobs | wc -l) )) ``` to force immediate "casting" to int. Is there a better way to take the output of a command substitution list and assign it to a variable as an integer?

Original source