如何防止bash使用内置命令? [英] How do I prevent bash to use a builtin command?

查看:86
本文介绍了如何防止bash使用内置命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试修复使用echo的脚本,即使用内置命令而不是命令,如何防止这种情况发生?

I'm trying to fix a script that use echo, that is using the builtin command instead of the command, how can I prevent that?

我知道我可以做/bin/echo来强制使用它,但是我不想对路径进行硬编码(出于可移植性).

I know I can do /bin/echo to force the usage of that, but I wouldn't like to hardcode the path (for portability).

我以为是这样的:

$ECHO=`which echo`
$ECHO -e "text\nhere"

但是which echo返回:"echo:shell内置命令".

but which echo returns: "echo: shell built-in command".

我最终定义了一个echo函数,该函数按照@Kenster的建议使用env.这样,我无需修改调用以在脚本中回显.

I've ended up defining an echo function that uses env as @Kenster recommends. This way I don't need to modify the calls to echo in the script.

echo() {
  env echo $*
}

# the function is called before the built-in command.
echo -en "text\nhere"

推荐答案

使用env程序. Env是一个命令,它将在可能已修改的环境下启动另一个程序.因为env是一个程序,所以它无权访问shell内建程序,别名和其他功能.

Use the env program. Env is a command which launches another program with a possibly modified environment. Because env is a program, it doesn't have access to shell builtins, aliases, and whatnot.

此命令将运行echo程序,并在您的命令路径中进行搜索:

This command will run the echo program, searching for it in your command path:

$ env echo foo

您可以通过在运行echoenv echo时使用strace监视系统调用来验证这一点:

You can verify this by using strace to monitor system calls while running echo vs env echo:

$ strace -f -e trace=process bash -c 'echo foo'
execve("/bin/bash", ["bash", "-c", "echo foo"], [/* 16 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7f153fa14700) = 0
foo
exit_group(0)                           = ?

$ strace -f -e trace=process bash -c 'env echo foo'
execve("/bin/bash", ["bash", "-c", "env echo foo"], [/* 16 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7f474eb2e700) = 0
execve("/usr/bin/env", ["env", "echo", "foo"], [/* 16 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7f60cad15700) = 0
execve("/usr/local/sbin/echo", ["echo", "foo"], [/* 16 vars */]) = -1 ENOENT (No such file or directory)
execve("/usr/local/bin/echo", ["echo", "foo"], [/* 16 vars */]) = -1 ENOENT (No such file or directory)
execve("/usr/sbin/echo", ["echo", "foo"], [/* 16 vars */]) = -1 ENOENT (No such file or directory)
execve("/usr/bin/echo", ["echo", "foo"], [/* 16 vars */]) = -1 ENOENT (No such file or directory)
execve("/sbin/echo", ["echo", "foo"], [/* 16 vars */]) = -1 ENOENT (No such file or directory)
execve("/bin/echo", ["echo", "foo"], [/* 16 vars */]) = 0
arch_prctl(ARCH_SET_FS, 0x7f0146906700) = 0
foo
exit_group(0)                           = ?

这篇关于如何防止bash使用内置命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆