Home > Software engineering >  Trap and read $BASH_COMMAND but with yes/no
Trap and read $BASH_COMMAND but with yes/no

Time:11-01

I am trying to run a simple script in debug mode.

#!/bin/bash
trap 'read -p "run: $BASH_COMMAND"'  DEBUG
command 1
command 2




 **Current output:** 
run: command 1 <press enter and the command executes>
run: command 2 <press enter and the command executes>

But I want to run this in a loop asking yes/no before every execution

Expected output:

run: command 1 yes/no? <input 'yes'   enter and the command executes>
run: command 2 yes/no? <input 'yes'   enter and the command executes>

I tried

trap [['read -p "run: $BASH_COMMAND" && "continue [y/n]" ' ; echo $REPLY)" == [Yy]* ]] && echo Continuing || echo Stopping DEBUG

but I am not able to figure it out.

Basically, I am trying to perform two read operation in trap/debug command and on second read i want to perform logical operation before executing.

Could anyone point me in the right direction, please? May be process substitution

CodePudding user response:

Perhaps something like this

#! /bin/bash

confirm() {
    read -rp "run: $BASH_COMMAND, continue [y/n]: "
    if [[ "$REPLY" == [Yy]* ]]; then
        echo Continuing
    else
        echo Stopping DEBUG
        exit
    fi
}

trap confirm  DEBUG
command 1
command 2
  • Related