Get a list of all user's commands from a non-interactive shell
0
votes
1
answer
105
views
I am writing a script that would automatically suggest some new aliases/functions to be added to a user's shell config. Before doing that, however, I would like to make sure the aliases being suggested would not override commands that are already present.
For regular executables, that is as simple as checking
$PATH
(or using command
or type
, etc.).
However, I've run into the issue that some other commands, such as aliases and shell functions, are lost in a non-interactive shell.
sh
#!/usr/bin/env sh
alias
Running the above file with ./print_aliases.sh
will not produce any output.
A couple of workarounds I found:
- source print_aliases.sh
will work as needed. \
However, this requires the user to source
the script every time, and requires any other script using this one to itself be sourced.
- I could parse the user's .bashrc
/.zshrc
/etc. \
This is highly unreliable and unportable - hard to guess which files the user has sourced and in what ways.
- I could attempt to source the user's shellrc. Something like this would work:
sh
#!/usr/bin/env sh
source $HOME/.bashrc
alias
This suffers from the same issue as the manual parsing approach, though.
- I've also tried playing around with spawning new shells, $SHELL --login
. That seems to just spawn a new shell marked as a login shell, but doesn't actually source the user's configs, so still no aliases.
Ideally, I would like a script that prints all commands either (1) present in the environment it's run in, or (2) present in the user's default login shell without any interaction.
Is there an (at least somewhat) portable and reliable way to achieve what I'm trying to do?
Asked by zoickx
(51 rep)
Jul 18, 2024, 09:42 PM
Last activity: Jul 19, 2024, 12:23 PM
Last activity: Jul 19, 2024, 12:23 PM