Reputation: 2250
I'm trying to find all aliases that the current shell possesses (in a C program). I've tried system("alias")
, popen("alias", "r")
and execvp("alias", ...)
, the latter of which doesn't work at all (because alias
is a shell-specific command) and the first two of which run that command in a subshell (which is sh
and not bash
) -> there, aliases are disabled because they are defined in my ~/.bashrc
. Executing bash
and reading the output of alias
isn't possible either because bash
will only go to the alias definitions if it is in interactive mode.
If I do run bash
in interactive mode, I get a huge delay time and a prompt output that I want to avoid.
Basically, what I want, is to have similar behaviour as time(1)
. It looks up current aliases without even executing any command! (it will fork only once, that is, for the passed command)
Crawling the Internet was to no avail.
Question: How do I look up all aliases in the current shell? Will there be any portability issues? If yes, how to avoid them?
Regards.
Upvotes: 1
Views: 213
Reputation: 185852
I just downloaded and built GNU time on my Mac. To my surprise and chagrin, it doesn't read aliases from the parent bash, whereas the built-in time
does.
$ alias frodo=ls
$ ./time frodo
./time: cannot run frodo: No such file or directory
Command exited with non-zero status 127
0.00user 0.00system 0:00.00elapsed ?%CPU (0avgtext+0avgdata 819200maxresident)k
0inputs+0outputs (0major+59minor)pagefaults 0swaps
$ time frodo
AUTHORS INSTALL Makefile.in config.cache configure* error.o getopt.o getpagesize.h mkinstalldirs* resuse.h stamp-vti time.c time.texi version.texi
COPYING Makefile NEWS config.log configure.in getopt.c getopt1.c install-sh* port.h resuse.o texinfo.tex time.info version.c wait.h
ChangeLog Makefile.am README config.status* error.c getopt.h getopt1.o mdate-sh* resuse.c stamp-v time* time.o version.o
real 0m0.005s
user 0m0.002s
sys 0m0.002s
$
I suspect there's something undocumented is passing under the table to help the builtin time
see aliases (or BSD provides something that GNU time won't or can't make use of).
EDIT: Prompted by Tom Tanner's answer (+1 Tom), I just realised that time frodo
doesn't invoke /usr/bin/time
(as suggested by which time
), and that explicitly running /usr/bin/time frodo
also fails, so it must be that entering time
by itself invokes a bash builtin command.
Upvotes: 2
Reputation: 9354
You can't. time is a built-in and it can access the aliases which are stored internally to the shell instance that is running. if you need to work out what the shell will execute, you need to run which or something similar.
time isn't doing anything clever or secret. It's just a prefix to the command to make the shell print out some timing information.
Upvotes: 2