bash: get list of commands starting with a given s

2020-02-20 04:57发布

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.

8条回答
2楼-- · 2020-02-20 05:51

JacobM's answer is great. For doing it manually, i would use something like this:

echo $PATH  | tr : '\n' | 
 while read p; do 
  for i in $p/mod*; do
   [[ -x "$i" && -f "$i" ]] && echo $i     
  done
 done

The test before the output makes sure only executable, regular files are shown. The above shows all commands starting with mod.

查看更多
对你真心纯属浪费
3楼-- · 2020-02-20 05:52

Interesting, I didn't know about compgen. Here a script I've used to do it, which doesn't check for non-executables:

#!/bin/bash
echo $PATH | tr ':' '\0' | xargs -0 ls | grep "$@" | sort

Save that script somewhere in your $PATH (I named it findcmd), chmod u+w it, and then use it just like grep, passing your favorite options and pattern:

findcmd ^foo   # finds all commands beginning with foo
findcmd -i -E 'ba+r'  # finds all commands matching the pattern 'ba+r', case insensitively
查看更多
登录 后发表回答