0

So I'm writing this simple script to pull the process ID of my app, and then run the "top" command with the value I pulled as the -p argument. The goal is to run the "top" command using the pid of our app to see what our CPU and MEM usage is like when tests are run overnight (outputting results to a file).

My script:

#!/bin/bash
pid=`pidof -s com.example.app`
echo $pid
top -o %CPU,%MEM -p $pid > /data/topresults.txt

I can see the echo outputting the right pid for my app, but when I try to push this script to the device and run it in the shell via 'sh data/gettop.sh', I see the following outputted logs:

PS C:\Users\user\AppData\Local\Android\Sdk\platform-tools> ./adb shell                                               
fca_dv2:/ # sh data/gettop.sh 
5889
'op: bad -p '5889
             ^

What exactly is failing here? Is it saying there's an extra ' symbol ahead of the pid I fed it, or is something else going on here? I'm not sure why it's failing to use the variable as the argument here.

Thanks for the assistance!

mbob98
  • 79
  • 7
  • 2
    Notice the single quote at the start of the error message? That indicates the variable value ends with a carriage return: `5889\r` -- your script file probably has DOS-style `\r\n` line endings. Pass your script through `dos2unix` to remove them – glenn jackman May 15 '23 at 19:35
  • If instead of `echo $pid` you used `declare -p pid` you'd see that already, with it writing something like `declare -- pid=$'5889\r'`. BTW, don't use `sh` to run a `bash` script -- they're two different interpreters, not two names for the same thing (even when `sh` and `bash` are linked together, it turns off some features when started with the `sh` name). Either use `#!/bin/sh` at the top of the script to make it a sh script, or if you're going to keep using `#!/bin/bash`, use `bash yourscript` to run it. Or, better, just run `./yourscript` not `sh yourscript` or `bash yourscript` at all. – Charles Duffy May 15 '23 at 19:37
  • (you can also use `bash -x yourscript` to log each command as it's run; the output from those logs would also show you the unwanted carriage returns as `\r` sequences). – Charles Duffy May 15 '23 at 19:55
  • @glennjackman dos2unix conversion fixed the issue - thank you so much for this comment! I didn't see anything online about "dos2unix" anywhere. – mbob98 May 15 '23 at 20:02

0 Answers0