1

I have this:

ql_remove_locks(){
  local pid="$$";
  declare -i count=0;
  ql_pid="$pid" ql_node_ls_all | while read line; do
    count=$((count+1));
    echo "count: $count";
    echo "deleting lock: $line";
    rm -rf "$line";
  done;
  echo "quicklock: $count lock(s) removed."
}

I am getting this output:

count: 1
deleting lock: /Users/alexamil/.quicklock/locks/a.lock
quicklock: 0 lock(s) removed.

I have tried so many things, still 0 always gets logged:

quicklock: 0 lock(s) removed.

Why is the count 0 instead of 1 in the echo statement?

codeforester
  • 39,467
  • 16
  • 112
  • 140

1 Answers1

1

Commands in a pipeline are run in subshells. The while loop is in a subshell, with its own copies of variables, and modifying $count there doesn't propagate back to the parent shell.

You can switch the pipe to a redirection + process substitution to work around this.

while read line; do
  count=$((count+1))
  echo "count: $count"
  echo "deleting lock: $line"
  rm -rf "$line"
done < <(ql_pid="$pid" ql_node_ls_all)

NB: The semicolons are superfluous.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578