Skip to content
Fragmented Development

Defining bash functions inside functions

I tend to do a lot of things with some terrible, terrible bash scripts. Backups, listening to music, creating temporary virtual machines... and also, listening through my podcast backlog. This last one gets pretty complicated, and while looking into how to manage it, I discovered a bash script technique that surprised me.

I have several bash functions that are only necessary if the prompt I'm in has "podcast mode" enabled. They will be short aliases like "play", "next" that should probably be as localized as possible, and could interfere with other similar functions (like listening to music, for instance). So they need to be defined when I'm listening to podcasts, but should not be present in other states. So, how are we going to only define functions when they're necessary?

If you place function definitions inside another function, they only get defined if the parent function is called! You can have multiple functions filled with overlapping function definitions, and call the one you want.

function podcast_functions {
    function play {
        # Call media player at 1.5x speed
    }

    function next {
        # Randomly select next podcast
    }

    function remove_last {
        # Delete last listened
    }
}

function media_player_functions {
    function play {
        # Call media player at normal speed
    }

    function next {
        # Move to the next song in the playlist
    }

    # No remove_last function, it isn't needed in a media player
}

This should let me add different versions of the same bash functions based on the context of the terminal session, which is convenient for my particular weird use cases.

Here's an example of it in use:

windigo@nyota | ~
→ play
bash: play: command not found
windigo@nyota | ~
→ podcast_functions
windigo@nyota | ~
→ play
[Playing podcast file]

Tags: terminal bash


Add Your Comment