【发布时间】: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