我可以在我的 shell(恰好是bash
)中输入什么来列出所有被识别的命令?
另外,这是否因外壳而异?还是所有 shell 都只有一个它们识别的命令的“目录”?
其次,不同的问题,但我怎样才能覆盖其中的任何一个?换句话说,我如何编写自己的view
命令来替换我的 Ubuntu 系统上现有的命令,该命令似乎只是加载vim
.
Rah*_*til 80
您可以使用compgen
compgen -c # will list all the commands you could run.
Run Code Online (Sandbox Code Playgroud)
供参考:
compgen -a # will list all the aliases you could run.
compgen -b # will list all the built-ins you could run.
compgen -k # will list all the keywords you could run.
compgen -A function # will list all the functions you could run.
compgen -A function -abck # will list all the above in one go.
Run Code Online (Sandbox Code Playgroud)
Gil*_*il' 18
shell 知道四种命令。
~/.bashrc
用于 bash)中定义。cd
更改当前目录、set
更改选项和位置参数、export
更改环境……)。大多数 shell 提供基本相同的内置函数,但每个 shell 都有一些基本集的扩展。PATH
环境变量包含搜索程序目录的冒号分隔的列表。如果存在多种类型的同名命令,则执行上述顺序中的第一个匹配¹。
您可以通过运行查看名称对应的命令类型type some_name
。
您可以通过alias
不带参数运行内置程序来列出别名。无法列出适用于所有 shell 的函数或内置函数。您可以在 shell 的文档中找到内置函数列表。
在 bash 中,set
内置函数会列出函数及其定义和变量。在 bash、ksh 或 zsh 中,typeset -f
列出函数及其定义。在 bash 中,您可以列出任何类型的所有命令名称compgen -c
。您可以使用compgen -A alias
,compgen -A builtin
compgen -A function
列出特定类型的命令。您可以传递一个额外的字符串来compgen
仅列出以该前缀开头的命令。
在zsh中,你可以列出一个给定类型的当前可用的命令echo ${(k)aliases}
,echo ${(k)functions}
,echo ${(k)builtins}
和echo ${(k)commands}
(即最后一个仅列出外部命令)。
以下 shell-agnostic 片段列出了所有可用的外部程序:
case "$PATH" in
(*[!:]:) PATH="$PATH:" ;;
esac
set -f; IFS=:
for dir in $PATH; do
set +f
[ -z "$dir" ] && dir="."
for file in "$dir"/*; do
if [ -x "$file" ] && ! [ -d "$file" ]; then
printf '%s = %s\n' "${file##*/}" "$file"
fi
done
done
Run Code Online (Sandbox Code Playgroud)
Bash 中有一个边缘情况:散列命令。
仅当哈希表中未找到该命令时,才执行 $PATH 中目录的完整搜索
尝试:
set -h
mkdir ~/dir-for-wat-command
echo 'echo WAT!' >~/dir-for-wat-command/wat
chmod +x ~/dir-for-wat-command/wat
hash -p ~/dir-for-wat-command/wat wat
wat
Run Code Online (Sandbox Code Playgroud)
该PATH
环境变量不包含~/dir-for-wat-command
,compgen -c
不显示wat
,但可以运行wat
。
如果要隐藏现有命令,请定义别名或函数。
¹例外:一些内置函数(称为特殊内置函数)不能被函数遮蔽——尽管 bash 和 zsh 在其默认模式下在这一点上不符合 POSIX。
试试这个,使用bash:
( # usage of a sub processus: the modificaion of PATH variable is local in ( )
PATH+=:EOF # little hack to list last PATH dir
printf '%s\n' ${PATH//:/\/* }
)
Run Code Online (Sandbox Code Playgroud)