Is it possible to get, using Bash, a list of commands starting with a certain string?
I would like to get what is printed hitting <tab> twice after typing the start of the command and, for example, store it inside a variable.
相关问题
- Is shmid returned by shmget() unique across proces
- how to get running process information in java?
- JQ: Select when attribute value exists in a bash a
- Error building gcc 4.8.3 from source: libstdc++.so
- Why should we check WIFEXITED after wait in order
What is listed when you hit are the binary files in your PATH that start with that string. So, if your PATH variable contains: PATH=/usr/local/bin:/usr/bin:/bin:/usr/games:/usr/lib/java/bin:/usr/lib/java/jre/bin:/usr/lib/qt/bin:/usr/share/texmf/bin:.
Bash will look in each of those directories to show you the suggestions once you hit . Thus, to get the list of commands starting with "ls" into a variable you could do: MYVAR=$(ls /usr/local/bin/ls* /usr/bin/ls* /bin/ls*) Naturally you could add all the other directories I haven't.
Iterate over the $PATH variable and do
ls beginningofword*
for each directory in the path?To get it exactly equivalent, you would need to filter out only executable files and sort by name (should be pretty easy with ls flags and the sort command).
A fun way to do this is to hit
M-*
(Meta is usually left Alt).As an example, type this:
Then hit
M-*
:You can read more about this in
man 3 readline
; it's a feature of thereadline
library.If you want exactly how bash would complete
compgen completes using the same rules bash uses when tabbing.
You should be able to use the compgen command, like so:
For example, "compgen -A builtin l" returns
You can use other keywords in place of "builtin" to get other types of completion. Builtin gives you shell builtin commands. "File" gives you local filenames, etc.
Here's a list of actions (from the BASH man page for complete which uses compgen):
Just for fun, another manual variant:
where
pattern
specifies the file name pattern you want to use. This will miss commands that are not globally executable, but which you have permission for.[tested on Mac OS X]
Use the
-or
and-and
flags to build a more comprehensive version of this command:will pick up files you have permission for by virtue of owning them. I don't see a general way to get all those you can execute by virtue of group affiliation without a lot more coding.