Search for command with wildcard

My favorite way is to use compgen -c. For example, to find all commands that contain mount:

$ compgen -c | grep mount
gvfs-mount
mmount
ideviceimagemounter
grub-mount
humount
hmount
umount
mountpoint
mount
fusermount
umount
mount.ntfs
mount.lowntfs-3g
mount.cifs
umount.udisks
mount.nfs
umount.nfs
mount
mount.ntfs-3g
mount.fuse
showmount
rpc.mountd
mountesp
umount.udisks2
mountstats
automount

What's good about compgen -c is that it also finds aliases, user functions and Bash built-in commands, for example:

$ alias aoeuidhtn='echo hi'
$ compgen -c | grep aoeuidhtn
aoeuidhtn
$ my-great-function() { printf "Inside great function()\n"; }
$ compgen -c | grep great
my-great-function
$ compgen -c | grep '^cd$'
cd

Also, compgen is a part of Bash, so it's always available. As described by help compgen:

Display possible completions depending on the options.

Intended to be used from within a shell function generating possible completions.  If the optional WORD argument is supplied, matches against WORD are generated.

Exit Status:
Returns success unless an invalid option is supplied or an error occurs.


#! /bin/bash
s=$1  # e.g. mount
IFS=:
for p in $PATH ; do
    ls "$p/"*"$s"* 2>/dev/null
done

Setting $IFS to : makes the for correctly iterate over the members of $PATH. Redirecting stderr to /dev/null hides error messages for directories that contain no matches.

Tags:

Bash