Search code examples
c++linuxbashshellsystem

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


I am trying a call a shell script from a cpp program and passing some variables to the script. The script simply copies a file from one directory to another. I want to pass the name of the file, the source directory and the destination directory to shell script from the cpp program. I get the error omitting directory "/" when I try. Please how can I fix this

C++ Code:

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 Script code:

SPATH=${spath}

DPATH=${dpath}

FILE=${filename}

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

Solution

  • Your C++ code and the shell script are not in the same scope. In other words, variables in C++ will not be visible in your script, and when passed to the script, the variables will be renamed as $1, $2, and so on.

    To fix it, you can change your code to the following:

    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);
    

    In this way, the spath will be substituted by the value of it, which is then passed to your script.

    In your script, you can use:

    cp $1/$2 $3/$2
    

    or if you prefer:

    SPATH=$1
    
    DPATH=$2
    
    FILE=$3
    
    cp ${SPATH}/${FILE} ${DPATH}/${FILE}
    

    The script will never know the variable name in the C++ code. When the script is called, the parameters will be replaced by $1, $2...