0

I am totally new to bash scripting. I am wondering if there's a way that I can create a reference for the following code block:

read -t5 -n1 -r -p 'Press any key or wait five seconds...' key
if [ "$?" -eq "0" ]; then
    echo 'A key was pressed.'
else
    echo 'Five seconds passed. Continuing...'
fi

Is there a way I can give this block of code a reference point and execute it using the reference several times throughout the rest of the script?

Would it be easier/better to create a separate script using this particular code and then reference it in the rest of the script I'm writing using include? e.g. Bash: How _best_ to include other scripts?

Thanks!

AveryFreeman
  • 1,061
  • 2
  • 14
  • 23
  • 2
    Are you looking for a function? `foo() { cmds; }` – William Pursell Nov 26 '17 at 13:31
  • 1
    Also, you can simplify exit status testing (note that `[` is actually a command and `if` tests its exit code): `if read -t5 ...; then echo Key pressed; else echo Timeout; fi`. – randomir Nov 26 '17 at 13:39
  • Tangentially, note that the very purpose of `if` is to run a command and examine its exit code. In other words, `cmd; if [ "$?" = "0" ]; then ...` is more idiomatically and elegantly written `if cmd; then ...` – tripleee Nov 26 '17 at 18:58

1 Answers1

4

Yes, there is a way to do that: Make it a function.

ReadKey() {
    read -t5 -n1 -r -p 'Press any key or wait five seconds...' key
    if [ "$?" -eq "0" ]; then
        echo 'A key was pressed.'
    else
        echo 'Five seconds passed. Continuing...'
    fi
}

And then call it:

ReadKey
melpomene
  • 84,125
  • 8
  • 85
  • 148