Bash aliases zijn handig. Maar wat nóg handiger is: snelle commando's die je kunt intypen terwijl je in het project zelf zit!
Dit kun je doen met een simpele command not found handle in Bash. Heel simpel.
vim ~/.bashrc
Ga vervolgens naar de onderkant van het bestand en plak de volgende code:
command_not_found_handle() {
local cmd="$1"
local alias_dir="$PWD/.bash_aliases"
if [[ -x "$alias_dir/$cmd" ]]; then
"$alias_dir/$cmd" "${@:2}"
return $?
elif [[ "$cmd" == "custom_cmd" ]]; then
_custom_command_autocomplete
return 0
fi
echo "bash: $cmd: command not found" >&2
return 127
}
_custom_command_autocomplete() {
local cur alias_dir cmd_list
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
alias_dir="$PWD/.bash_aliases"
# List executable files in .bash_aliases directory
if [[ -d "$alias_dir" ]]; then
cmd_list=$(find "$alias_dir" -maxdepth 1 -type f -executable -printf '%f ')
COMPREPLY=( $(compgen -W "${cmd_list}" -- ${cur}) )
fi
return 0
}
complete -o default -o bashdefault -I -F _custom_command_autocomplete
Wat dit doet:
./.bash_aliases erachter, om te zien of daar een bestand staat die gelijk is aan de command die je ingetypt hebtHet is dus een beetje een hack, maar het werkt!
Vergeet extensies zoals .sh; maak gewoon een bestand aan voor de opdracht die je wilt creëren. Bijvoorbeeld: hello-world
mkdir -p ./.bash_aliases
echo '#!/bin/sh' > ./.bash_aliases/hello-world
echo 'echo Hello, World!' >> ./.bash_aliases/hello-world
chmod +x ./.bash_aliases/hello-world
Typ in je terminal (terwijl je in de directory zit met de .bash_aliases dir) hello-world.
Als je nu de tekst Hello, World! terugkrijgt, dan weet je dat het heeft gewerkt! 🥳