Applescript – Fixing Blank Shell Output to Variable

applescriptcommand line

Hi I'm trying to get the cpuValue but I get "" for the variable.

set cpuValue to ""
getProcessPercentCPU("Safari")

on getProcessPercentCPU(someProcess)
    set cpuValue to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & someProcess & "$/ {print $1}'"
end getProcessPercentCPU

log "output:" & cpuValue

Output

""

Best Answer

AppleScript treats variables created with set as local by default (although the documentation isn't totally clear IMO). This means that the cpuValue variable inside on getProcessPercentCPU is local to that handler, and different from the variable with the same name in the outer scope.

Essentially, you have two different variables that just happen to have the same name, one set to "", the other to the CPU percentage for the Safari process.

You could solve this by adding global cpuValue inside the handler, but returning values in global variables isn't good programming practice. It's almost always better to return values like a function:

set cpuValue to getProcessPercentCPU("Safari")
    
on getProcessPercentCPU(someProcess)
    set processPercentCPU to do shell script "/bin/ps -xco %cpu,command | /usr/bin/awk '/" & someProcess & "$/ {print $1}'"
    return processPercentCPU
end getProcessPercentCPU
    
log "output:" & cpuValue