Implement batch option --yes in bash script
You could use yes(1), which shouldn't require any modification to your script at all.
$ grep . test.sh
#!/bin/bash
read -rp 'What say you? ' answer
echo "Answer is: $answer"
read -rp 'And again? ' answer2
echo "Answer 2 is: $answer2"
$
$ yes | ./test.sh
Answer is: y
Answer 2 is: y
It will repeat a specified expletive indefinitely, if none is specified it will default y
.
If you use read
only for these questions, and the variable is always called answer
, replace read
:
# parse options, set "$yes" to y if --yes is supplied
if [[ $yes = y ]]
then
read () {
answer=y
}
fi
I would put the whole decision logic in a function, both checking the auto-mode and possibly querying the user. Then call just that from the main level in each case. want_act
below returns truthy/falsy in itself, no need for a string comparison in the main level and it's clear to the reader what the condition does.
#!/bin/bash
[[ $1 = --yes ]] && yes_mode=1
want_act() {
[[ $yes_mode = 1 ]] && return 0
read -r -p "Include step '$1' (y/n)? " answer
[[ $answer = [Yy]* ]] && return 0
return 1
}
if want_act "frobnicate first farthing"; then
echo "frobnicating..."
fi