I was discussing with my friend on how the commands are parsed in the shell, and he told me that bash searches the command in following order
- List of aliases
- List of shell keywords
- List of user defined functions
- List of shell built in functions
- List of directories specified in the PATH variable , from left to right.
I know aliases can be found by issuing the alias command. PATH variable contents can be found using echo $PATH command.
Can you please tell me which commands do I need to use ?
- To list all shell keywords
- To list all user defined functions
- To list of shell built in functions
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can also use compgen in bash:
compgen -klists keywordscompgen -borenablelists builtinscompgen -A functionordeclare -Flists functionscompgen -aoraliaslists aliasescompgen -clists commandscompgen -vlists variablescompgen -eorexportlists exported variables
Method 2
In Bash:
-
man bash | grep -10 RESERVEDlists reserved words:! case coproc do done elif else esac fi for function if in select then until while { } time [[ ]]
-
declare -Fandtypeset -Fshows function names without their contents. -
enablelists builtin shell commands (I don’t think these are functions as such).So doesman builtins
Method 3
With zsh:
PATH= type -m '*'
Will tell you all 3.
In bash, to list the keywords, you can do:
complete -A keyword :
and then type : <Tab><Tab>
For builtins, replace keyword with builtin above and for functions, I’ll let you guess.
Method 4
The answer for the 2nd question in case of bash or zsh: declare -f.
Method 5
In bash
-
keywords (reserved words):
compgen -A keyword # or: compgen -k
-
functions (defined at the point of execution):
compgen -A function # Only names. declare -F # Only names but prefixed with `declare -f`.
declare -f # Full function definition.
-
builtins
compgen -A builtin # Only names. enable # Names prefixed with `enable ` man builtins # Only if the correct man package is installed.
There are some other keywords for compgen as well: alias, commands, variables, export, etc.
A list of possible compgen -A options may be found by completing:
compgen -A # and press Tab (Maybe twice vary by configuration).
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0