[英]Calling a shell script from a C++ program with parameters
我正在尝试从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}
您的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
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.