brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: declare -f prints the code of a shell function you loaded earlier

Shell
~/tips/tip-shell-declare-f-show-function

declare -f mkcd

See what a function in your shell really does, and where it came from.

A command behaves oddly and type says it is a function, from some file your shell loaded at startup. declare -f shows you the code right away.

Give it the name of the function:

declare -f mkcd
# mkcd ()
# {
#     mkdir -p "$1" && cd "$1"
# }

Bash prints the function as it parsed it, neatly indented. Without a name, declare -f prints every function in the shell, and declare -F lists only the names, which is shorter and handy with grep.

To find out which file defined it, bash needs one extra option:

shopt -s extdebug
declare -F mkcd
# mkcd 12 /home/me/.bashrc
shopt -u extdebug

That gives the line number and the file. I find that the quickest way to track down a function that some plugin or old dotfile slipped in.

The printed code is a reconstruction, so comments are gone and the layout may differ from the file. Also note that extdebug changes other things for debuggers, so switch it off again afterwards. In zsh, functions mkcd and whence -v mkcd do the same jobs.

Further reading: Bash manual: Bash Builtins (declare), Bash manual: The Shopt Builtin

More Shell tips zmv -n '(*).log' '$1.txt' zoxide query -ls project f=$(mktemp --suffix=.json) shopt globskipdots echo $EPOCHSECONDS All Shell tips (78) All topics

Link