【问题标题】:Calling a shell script from a C++ program with parameters从带有参数的 C++ 程序调用 shell 脚本
【发布时间】:2018-12-27 14:16:23
【问题描述】:

我正在尝试从 cpp 程序调用 shell 脚本并将一些变量传递给脚本。该脚本只是将文件从一个目录复制到另一个目录。我想将文件名、源目录和目标目录从 cpp 程序传递给 shell 脚本。当我尝试时,我得到了省略目录“/”的错误。请问如何解决这个问题

C++ 代码:

std::string spath="/home/henry/work/gcu/build/lib/hardware_common/";

std::string dpath="/home/henry/work/gcu/dll/";

std::string filename="libhardware_common.a";

std::system("/home/henry/work/gcu/build/binaries/bin/copy.sh spath dpath filename");

Shell 脚本代码:

SPATH=${spath}

DPATH=${dpath}

FILE=${filename}

cp ${SPATH}/${FILE} ${DPATH}/${FILE} 

【问题讨论】:

  • spath 和 dpath 并且不会在您的 C++ 代码中替换。它们将是文字spath 和dpath。也许您应该使用std::ostringstream 并将它们插入到与std::system 一起使用的命令中。您也应该显示更多的 shell 代码。我认为它有一些问题,但可能需要更多的contrext。
  • [teach-me] 你对 C 和 shell 中的字符串和变量名有一些误解。当您将 C 中的 "dpath" 字符串传递给 system() 时,它不会神奇地变成 "/home/henry/work/gcu/dll/"。 shell 也不能通过 C 变量名称访问命令行参数 - 在 shell 中查看 $1、$2 等等。

标签: c++ linux bash shell system


【解决方案1】:

您的 C++ 代码和 shell 脚本不在同一范围内。换句话说,C++ 中的变量在你的脚本中是不可见的,当传递给脚本时,这些变量将被重命名为$1、$2 等等。

要修复它,您可以将代码更改为以下内容:

std::string spath = "/home/henry/work/gcu/build/lib/hardware_common/";

std::string dpath = "/home/henry/work/gcu/dll/";

std::string filename = "libhardware_common.a";

std::string shell = "/home/henry/work/gcu/build/binaries/bin/copy.sh"

std::system(shell + " " + spath + " " + dpath + " " + filename);

这样,spath 将被它的值替换,然后传递给您的脚本。

在您的脚本中,您可以使用:

cp $1/$2 $3/$2

或者如果您愿意:

SPATH=$1

DPATH=$2

FILE=$3

cp ${SPATH}/${FILE} ${DPATH}/${FILE}

脚本永远不会知道 C++ 代码中的变量名。调用脚本时,参数会被替换为$1、$2...

【讨论】:

  • 请注意:如果spath、dpath 和filename 中有任何空格,则答案中的代码将中断。届时将需要更精细的方法。
  • @Arkadiy:或星号、美元符号或反引号......值得注意的是,这种事情在生产代码中非常罕见,因为它可能是安全漏洞的来源。 (至少,审查您的代码的人需要花一些时间来证明它不是。)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-01
  • 2011-06-30
  • 1970-01-01
  • 1970-01-01
  • 2018-11-18
  • 1970-01-01
  • 2016-05-02
相关资源
最近更新 更多