'faster coding in bash: one-liner templates

Using the bash is often tedious, not least because there is often some overhead. I want to speed up my bash coding with some kind of macro, since I am not the fastest typer.

An use case would be to copy a.out to some (sub)directories :

mkdir subdir{1..5}
echo "123" > a.out
for d in $(ls -d subdir*); do cd $d; pwd; cp ../a.out .; cd ..;done

where I repeatedly use the body

for d in $(ls $PATTERN); do $COMMAND ;done

with some $COMMAND in a broader context. One option to accelerate would be a bash function.

function loop () {
  for d in $(ls $1); do $2 ;done
}

But since the bash has an auto-completion mechanism and also the wonderful ctrl+r search, I wondered if there's a smart trick that utilized this mechanisms to make the body appear on the bash prompt directly. The ideal scenario would be to type some predefined keyword like loop in the bash and upon pressing TAB (or some other shortkey(s)) the body

for d in $(ls $PATTERN); do $COMMAND ;done

shows up in bash (and still can be manipulated).

To make clear what I'm thinking about: This is a standard feature in editors like vscode, where I can type func, a dropdown menu appears and I can select some body to get function ### (###) {###} written out. Such a macro would definitely help me in other situations, too, whenever I have to use the same body many times.

Any ideas? How do you deal with the mentioned overhead in bash?



Solution 1:[1]

Defining a completion function for the for keyword?

#!/bin/bash

_for() {
    COMPREPLY=()
    if [[ ${#COMP_WORDS[@]} == 2 ]]
    then
        COMPREPLY=( 'd in PATTERN; do COMMAND; done' )
    fi
}

complete -F _for for

Then try to type: for Tab

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1