
나는 에 따라 100% 정확한 bash 스크립트를 작성했습니다 https://www.shellcheck.net/#
. 코드를 수정한 다음 원하는 애플리케이션과 관련 PID를 CPU제한해야 합니다.
#!/bin/bash
INTERVAL=10
PROCESSES_TO_WATCH=gnome-shell
set -x
while sleep $INTERVAL; do
for process_name in $PROCESSES_TO_WATCH; do
pid_list=("$(pgrep "$process_name")")
# Don't do anything if no running process found
[ ${#pid_list[@]} -le 0 ] && continue
for pid in "${pid_list[@]}"; do
renice -n 19 -p "$pid" && cpulimit -p "$pid" -l 20
done
done
done
#EOF
문제:
출력은 renice 명령이 "$pid" 변수 값을 거부함을 보여줍니다.
+ sleep 10
+ for process_name in $PROCESSES_TO_WATCH
+ pid_list=("$(pgrep "$process_name")")
++ pgrep gnome-shell
+ '[' 1 -le 0 ']'
+ for pid in "${pid_list[@]}"
+ renice -n 19 -p '1797
3709
3074206'
renice: bad process ID value: 1797
3709
3074206
진전
해결책은 다음과 같습니다.사용하다잘못된스크립트
나는 renice -n 19 -p "$pid" && cpulimit -p "$pid" -l 20
로 바꿨다renice -n 19 -p $pid && cpulimit -p $pid -l 20
이제 출력에는 설계된 대로 작동하는 것으로 표시됩니다.
root@machine# /usr/local/bin/process-leash.sh
+ sleep 10
+ for process_name in $PROCESSES_TO_WATCH
+ pid_list=("$(pgrep "$process_name")")
++ pgrep gnome-shell
+ '[' 1 -le 0 ']'
+ for pid in "${pid_list[@]}"
+ renice -n 19 -p 1797 3709 3074206
1797 (process ID) old priority 0, new priority 19
3709 (process ID) old priority 0, new priority 19
3074206 (process ID) old priority 0, new priority 19
+ cpulimit -p 1797 3709 3074206 -l 20
Process 1797 detected
그 와중에 https://www.shellcheck.net/#
머리가 터지도록 비명을 지르고 있어요
$ shellcheck myscript
Line 14:
renice -n 19 -p $pid && cpulimit -p $pid -l 20
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
renice -n 19 -p "$pid" && cpulimit -p "$pid" -l 20
변수에 대한 따옴표가 왜 이 문제를 일으켰는지 아시나요?
답변1
쉘체크는 당신이 무엇을 하는지 모른다의미했다 , 따라서 일반적인 "단어 분리를 방지하기 위한 큰따옴표" 조언은 실제로 귀하에게 불리하게 작용합니다. 의 출력은 pgrep "$process_name"
공백으로 구분된 PID 목록을 반환합니다.필요배열에 할당할 때 단어로 분할되어야 하지만 할당 중에 값을 큰따옴표로 묶었기 때문에 항상 단일 문자열로 유지됩니다.