zoukankan      html  css  js  c++  java
  • Bash 中同名的内部命令和外部命令

    昨天有个人在 bug-bash 上问:为什么 [ --help 没有输出帮助信息。有人回答他了,原因是 coreutils 提供的 [ 命令才接受 --help 选项,Bash 自己的 [ 命令不接受任何选项。当你在 Bash 里执行 [ --help 时,当然优先执行的是内部命令 [,而不是外部命令 [,执行 /usr/bin/[ --help(在我的 Mac 上是在 /bin/[)才能获得他想要的帮助信息。

    其实除了 [,还有一些其它外部命令也会和 Bash 提供的内部命令同名,下面列举一下在我电脑上找到的这样的命令的名字:

    [
    alias
    bg
    cd
    command
    echo
    false
    fc
    fg
    getopts
    hash
    jobs
    kill
    printf
    pwd
    read
    test
    time
    true
    type
    ulimit
    umask
    unalias
    wait

    另外,从 Bash 4.4 开始,大部分的内部命令都开始接受 --help 选项,举两个例子,比如以前的 eval 和 source 是这样的:

    $ eval --help

    bash: eval: --: invalid option   

    eval: usage: eval [arg ...]

    $ source --help

    bash: source: --: invalid option

    source: usage: source filename [arguments]

    而在 Bash 4.4 里是这样的:

    $ eval --help

    eval: eval [arg ...]

        Execute arguments as a shell command.

        Combine ARGs into a single string, use the result as input to the shell,

        and execute the resulting commands.

        Exit Status:

        Returns exit status of command or success if command is null.

    $ source --help

    source: source filename [arguments]

        Execute commands from a file in the current shell.

        Read and execute commands from FILENAME in the current shell. The

        entries in $PATH are used to find the directory containing FILENAME.

        If any ARGUMENTS are supplied, they become the positional parameters

        when FILENAME is executed.

        Exit Status:

        Returns the status of the last command executed in FILENAME; fails if

        FILENAME cannot be read.

    我在 Bash 4.4 alpha 里试了一下,仍有少部分命令不接受 --help 选项,下面是我猜的原因:先说 echo,echo --help 只能输出 --help,输出别的就有兼容性问题了。还有一些命令比如 true false :,可能是因为自古以来这些命令就不接受任何选项吧,还有 test 和 [,我就不知道为什么了。 

    另外说个知识点,就是上面提问题的那个人还回贴说:我是通过 which [ 确认了在 Bash 里执行的 [ 是个外部命令的。随即有人纠正他,不能用 which 来判断一个命令是内部命令还是外部命令,因为 which 本身就是个外部命令,它的工作原理就是在 PATH 里查找外部命令,它不可能知道 [ 在 Bash 里是个内部命令,应该用 type 命令:

    $ which [

    /bin/[

    $ type [

    [ is a shell builtin

    而且 type 命令还可以把内部命令和外部命令按照 Bash 的查找顺序同时列出来:

    $ type -a [

    [ is a shell builtin

    [ is /bin/[

    最后再说一句,在 zsh 里 which 是个内部命令,而且它的功能和 type 很类似: 

    $ zsh

    $ which -a [

    [: shell built-in command

    /bin/[

  • 相关阅读:
    css 布局方式
    初识cv
    CSS 样式表{二}
    获取设备通讯录信息
    iOS Block界面反向传值小demo
    在iOS中如何正确的实现行间距与行高
    iOS开发- 获取本地视频文件
    view围绕圆心自转
    监测网络状态
    简单的九宫格算法与使用
  • 原文地址:https://www.cnblogs.com/ziyunfei/p/4832762.html
Copyright © 2011-2022 走看看