Looping Shell Script Recipe

  1. Change directory to where you would like to store the script output.
  2. Create a file named diagscript.sh with contents based on the following:
    #!/bin/sh
    set -e
    outputfile="diag_ps_$(date +"%Y%m%d_%H%M%S").log"
    while true; do
      date >> "${outputfile}" 2>&1
      # Change the command here, update '_ps_' in the file name above to match, and update the example in the next step:
      ps -elfyww >> "${outputfile}" 2>&1
      # Change the sleep time (in seconds) as needed:
      sleep 30
    done
  3. Manually confirm the looped command works (as some distributions support different flags). For example:
    ps -elfyww
  4. Make the script executable:
    chmod +x diagscript.sh
  5. Execute the script with nohup so that it's not interrupted if the user that started the script logs out (on some versions of Linux, you may need systemd-run instead), and send to the background with &:
    nohup ./diagscript.sh &
  6. After the script starts in the background, press ENTER to continue with the shell. If you'd like to watch the script output, you may tail it:
    tail -f diag*log
  7. When you are ready to stop the script, kill it by finding the process ID and then using that:
    kill ${PID}
    Alternatively, on Linux, use pkill:
    pkill -f diagscript.sh
  8. Upload diag*log