【问题标题】:Why can't the 'system' function in Linux run this shellscript?为什么 Linux 中的 'system' 函数不能运行这个 shellscript?
【发布时间】:2017-04-01 18:43:58
【问题描述】:

我遇到了关于系统功能的问题。如果我跑

echo -e '\x2f'

在shell中,输出是/,但是当我把命令放在C程序中时:

int main(int argc, char* argv[], char** envp)
{
    printf("The command is :%s\n",argv[1]);
    system( argv[1] );
    return 0;
}

输出是:

The command is :echo -e '\x2f'
-e \x2f

为什么system函数输出'-e \x2f'而不是'/'

顺便说一句,我使用 Python 输入 argv:

# I used \\ because python will transfer \x2f to / automatially
command="echo -e '\\x2f'"
p=process(executable='/home/cmd2',argv=   ['/home/cmd2',command])
print (p.readall())

【问题讨论】:

  • 因为脚本由/bin/sh 运行,而不是/bin/bash/bin/sh 不会解释与/bin/bash 相同的东西。

标签: linux shell command argv


【解决方案1】:

首先,echo 命令在shbash 之间的输出可能不同。
参考:https://unix.stackexchange.com/questions/88307/escape-sequences-with-echo-e-in-different-shells

bash -c "echo -e '\x2f'"
# Output : /
sh -c "echo -e '\x2f'"
# Output : -e /

为了让 Python 吐出同样的内容,下面的内容应该可以工作。
(供您参考,包含与子流程相同的实现)

import os
import subprocess

command = "echo -e '\\x2f'"

os.system( command )
# Output : -e /
subprocess.call( command , shell=True )
# Output : -e /

bashcmd = "bash -c \"echo -e '\x2f'\""

os.system( bashcmd )
# Output : /
subprocess.call( bashcmd , shell=True )
# Output : /

我不确定你是如何得到-e \x2f 作为输出的。

【讨论】:

  • bash -c \"echo -e '\x2f'\"可以工作,但我的情况是PATH变量已经清空,所以我使用echo -e '\x2f'构造/,但是/bin/bash也有/,也许我应该试试另一种方式
  • 您是否要设置 PATH 变量地面?可能值得检查this。无论如何,echo 可能不是你想采取的方式...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 1970-01-01
  • 2021-03-13
  • 1970-01-01
  • 2017-06-23
相关资源
最近更新 更多