从带有参数的C++程序中调用shell脚本

Calling a shell script from a C++ program with parameters

本文关键字:调用 shell 脚本 程序 C++ 参数      更新时间:2023-10-16

我正在尝试从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");

外壳脚本代码:

SPATH=${spath}
DPATH=${dpath}
FILE=${filename}
cp ${SPATH}/${FILE} ${DPATH}/${FILE} 

您的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。。。