Site Map - skip to main content - dyslexic font - mobile - text - print

Hacker Public Radio

Your ideas, projects, opinions - podcasted.

New episodes Monday through Friday.

hpr2096 :: Useful Bash functions - part 2

The further development of a Bash function that may be of use in your scripts

<< First, < Previous, Latest >>

Host Image
Hosted by Dave Morriss on 2016-08-15 is flagged as Explicit and is released under a CC-BY-SA license.
Listen in ogg, spx, or mp3 format. | Comments (2)

Part of the series: Bash Scripting

This is an open series in which Hacker Public Radio Listeners can share their Bash scripting knowledge and experience with the community. General programming topics and Bash commands are explored along with some tutorials for the complete novice.

Useful Bash functions - part 2


This is the second show about Bash functions. In this one I revisit the yes_no function from the last episode and deal with some of the deficiencies of that version.

As before it would be interesting to receive feedback on these versions of the function and would be great if other Bash users contributed ideas of their own.

Full Notes

Since the notes explaining this subject are long, they have been placed here.


Subscribe to the comments RSS feed.

Comment #1 posted on 2016-08-18T19:38:12Z by Ken Fallon

Here's me with the questions

Any special significance to the "%s" ?

Did not know this: ${FUNCNAME[0]}:
nor this: ${BASH_LINENO[0]}:
nor this: default="${2^^}"

Why do this:
printf -v prompt "$prompt" "[Y/n]"
and not this:
prompt="${prompt} [Y/n]"

Comment #2 posted on 2016-08-18T20:59:27Z by Dave Morriss

Some answers for you...

The "%s" is to be used in the prompt, as in:

if ! yes_no_mk3 'Do you want to continue? %s ' 'N'; then

It indicates the point at which the possible responses are shown in the prompt, using capitalisation to denote which is the default. I used '%s' because I'll be using the prompt string as a format definition for printf, and '%s' means "substitute a string of arbitrary length here".

The use of printf to write the prompt string allows the format to be defined when calling the function. The way it's laid out is:

printf -v prompt "$prompt" "[Y/n]"

because the '-v prompt' saves the result in variable 'prompt' (rewrites it).
The "$prompt" is the format string like when you do:

printf "The answer is %d\n" 42


The answer is 42

In this case however, the text to be substituted for '%s' is "[Y/n]".

None of this would work with:

prompt="${prompt} [Y/n]"

In my example function call above you'd get 'prompt' containing:

"Do you want to continue? %s [Y/n]"

No substitution would happen.

Of course you could redesign the function to simply append the "[Y/n]" to the prompt in the way you did. I just liked the flexibility of being able to place that part of the prompt where I liked.

Hope that helps.

Leave Comment

Powered by Comment Script