0

I want to run a cpp executable from my git for windows bash. I do not understand why I can run it with ./Main but I can't run it with bash Main or bash Main.exe. In the latter cases, I'm getting an error:

cannot execute binary file

main.cpp

#include<iostream>

int main()
{
std::cout<<"Hello World";
return 0;
}

script.sh

 echo "Hello from Bash script.."
    echo "Hostname:${1}"
    echo "Port:${2}"
    echo "Listing contents:"
    ls -a
    echo "Launching cpp executable:"
    path=$(pwd)
    echo "Current path:${path}"
    bash "${path}/Main"

To compile the C++ code, I'm using: g++ -o Main main.cpp.

What is the problem? Can someone explain please?

8
  • 1
    Where are you compiling your .cpp ? Commented Sep 21, 2018 at 14:02
  • 2
    I'm not sure there's much more to say than what bash already told you : it can't execute binary files. Commented Sep 21, 2018 at 14:03
  • 2
    of course. When you say bash filename you're telling bash to execute the shell commands found in the file: it is expected to be a text file containing a shell script. Commented Sep 21, 2018 at 14:09
  • 1
    you might want bash -c executableFile which spawns a bash shell to run the specified command, but you still need to provide the path to it, just like ./executableFile Commented Sep 21, 2018 at 14:11
  • 1
    For more details: gnu.org/software/bash/manual/bash.html#Invoking-Bash -- "If arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed to be the name of a file containing shell commands" Commented Sep 21, 2018 at 14:12

1 Answer 1

3

Just remove the bash on the last line of your script:

"${path}/Main"

Don't forget to make it executable.

chmod +x script.sh

It worked for me:

./script.sh hostname 80
Hello from Bash script..
Hostname:hostname
Port:80
Listing contents:
.       ..      Main        main.cpp    script.sh
Launching cpp executable:
Current path:/tmp/test
Hello World
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.