Verified Environment

Version
OSmacOS 13.2.1 (22D68) Darwin 22.3.0

What to do

Note
$ man screencapture
...
     -c      Force screen capture to go to the clipboard.
     -T      <seconds> Take the picture after a delay of <seconds>, default is 5.
     -x      Do not play sounds.
     -l      <windowid> Captures the window with windowid.
...
# Get window id
osascript -e "tell app \"APPLICATION_NAME\" to id of window 1"
  • window 1 means foreground window

Examples

Run command and take a screenshot

#!/bin/bash

terminal_app="iTerm2"

get_window_id() {
    osascript -e "tell app \"${1}\" to id of window 1"
}

"${@:2}"

case "${1}" in
    file)
        screencapture -T0 -x -l$(get_window_id "${terminal_app}") /tmp/$(date +'%Y%m%d-%H%M%S').png
        ;;
    clipboard)
        screencapture -T0 -x -l$(get_window_id "${terminal_app}") -c
        ;;
esac
$ run_command_and_take_screenshot.sh file find ./ -name '*.sh'

$ run_command_and_take_screenshot.sh clipboard find ./ -name '*.sh'