bashbash-trap

How to trap input to control the screenshot function?


I want to trap input to control the screenshot function.

vim myscreenshot.sh
screenshot(){
    ffmpeg -video_size 1920x1080 -framerate 25 -f x11grab -i :0.0+0,0   /tmp/out.mp4  
}
close(){
    echo "screenshot is over"
    exit
}    
trap 'screenshot'  ctrl+a #how to fix it?
trap 'close'  ctrl+b #how to fix it?

THe command trap 'screenshot' SIGINT can trap ctrl+c.
My requirement:input ctrl+a start screenshot function,ctrl+b stop screenshot function and exit after running bash myscreenshot.sh & in background.


Solution

  • As an alternative to using readline on a shell prompt, consider the following bash solution. Solution closely matching requirements. Basically:

    Loop Forever:

    It uses bash to read one-character at a time line delimiter is needed.

    Side note: Given program running in a window with dedicated terminal, the Ctrl/A and Ctrl/B can be replaced with something easier - just 'A' and 'B'.

    #! /bin/bash
    
    screenshot(){
        rm -f /tmp/out.mp4
        exec ffmpeg -video_size 1920x1080 -framerate 25 -f x11grab -i :0.0+0,0   /tmp/out.mp4
    }
    
    while true ; do
        a=""
        echo "Type CTRL/A to start"
        while [ "$a" != $'\x01' ] ; do
            read -N1 a
        done
        screenshot &
        sleep 3
        echo
        echo "Type CTRL/B to start"
        while [ "$a" != $'\x02' ] ; do
                read -N1 a
        done
        echo "Processing ..."
        kill $!
        bash myscreenshot.sh &
    done