如何让shell只执行外部echo,而不执行内置echo?

如何让shell只执行外部echo,而不执行内置echo?

system()我有一个使用库函数的C 程序。下面是源代码。

#include<stdlib.h>
int main()
{ 
    //Some code
    system("echo Hello World");
    //some code
    return 0;
}    

在运行这个 C 程序之前,我进行了更改,$PATH以便 /home/user1/bin/echo执行它而不是/bin/echo

export PATH="/home/user1/bin"

然而,当我运行 C 程序时,它没有执行/home/user1/bin/echo

是不是因为echo是一个shell built-in所以shell没有尝试去echo查找$PATH

如果是这样,在运行该程序之前我可以在 shell 中进行任何更改,以便echo在其中搜索$PATH而不是使用内置的echo.

答案1

command绕过函数,但不绕过 shell 内置函数。最安全的方法是使用完整路径:

system("/home/user1/bin/echo Hello world!")

如果你不能这样做,请尝试exec内置:

system("exec echo Hello World!")

例如:

$ cat foo.c       
#include<stdlib.h>
int main()
{ 
    //Some code
    system("exec echo --help");
    system("command echo --help");
    system("echo --help");
    //some code
    return 0;
}  
$ gcc -o foo foo.c
$ ./foo
Usage: echo [SHORT-OPTION]... [STRING]...
  or:  echo LONG-OPTION
Echo the STRING(s) to standard output.

  -n             do not output the trailing newline
  -e             enable interpretation of backslash escapes
  -E             disable interpretation of backslash escapes (default)
      --help     display this help and exit
      --version  output version information and exit

If -e is in effect, the following sequences are recognised:

  \\      backslash
  \a      alert (BEL)
  \b      backspace
  \c      produce no further output
  \e      escape
  \f      form feed
  \n      new line
  \r      carriage return
  \t      horizontal tab
  \v      vertical tab
  \0NNN   byte with octal value NNN (1 to 3 digits)
  \xHH    byte with hexadecimal value HH (1 to 2 digits)

NOTE: your shell may have its own version of echo, which usually supersedes
the version described here.  Please refer to your shell's documentation
for details about the options it supports.

Report echo bugs to [email protected]
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'echo invocation'
--help
--help

第二次和第三次system调用运行了内置函数echo,它不支持该--help标志。第一个运行/bin/echo,在我的例子中是由 GNU 提供的,它确实支持该--help标志。

man 3 system(POSIX):

The environment of the executed command shall be as if a child  process
were created using fork(), and the child process invoked the sh utility
using execl() as follows:

      execl(<shell path>, "sh", "-c", command, (char *)0);
where <shell path> is an unspecified pathname for the sh utility.

如果你在Linux:

system()  executes a command specified in command by calling /bin/sh -c
command, and returns after the  command  has  been  completed.   During
execution  of  the  command,  SIGCHLD  will  be blocked, and SIGINT and
SIGQUIT will be ignored.

由于/bin/sh -c是 明确使用的,因此您无法通过任何正常方式影响它 - 您可以替换/bin/sh.那将使用打桩机来弹出泡沫包装。

答案2

如果您使用的是 bash,您可以使用以下命令启用和禁用内置 shell 命令enable

enable -n echo

禁用内置 echo 命令。

答案3

有一个command命令可以做到这一点。显然,你不能。

system()顺便说一句,如果您关心安全问题,请务必小心。

相关内容