-1

In c++ is there a way to run a command in a program that has been opened using system(), all this being done programatically.

ie:

open git bash

system("start \"\" \"c:\\Program Files\\Git\\bin\\sh.exe\" --login -i");

then within the new opened git bash window cd back two directories

"cd ../../" 
Matt Jameson
  • 582
  • 3
  • 16
  • Theoretically, it completely depends on how your child program is designed, and it is nothing related with C++ language. I have no idea on how does git bash accepts commands, you may refer to its user manual. – jiandingzhe Sep 13 '18 at 09:16
  • yeah it accepts cd ../../ – Matt Jameson Sep 13 '18 at 09:17
  • Your question is to broad... Yes it is possible. your simple example you can just pass the command you want to be executed as a shell argument with `-c` (if it is a bash). However, this is probalby not what you want... So it depends on your target application... If the application uses stdin then you can redirect the pipe and send strings to the target application. There are libraries for that purpose, e.g. [boost::process](https://www.boost.org/doc/libs/1_68_0/doc/html/process.html). – user1810087 Sep 13 '18 at 09:23
  • I just want to open the git bash window and go 2 directories back within it mate, programatically – Matt Jameson Sep 13 '18 at 09:25
  • do you on windows? – apple apple Sep 13 '18 at 09:27
  • according to [this](https://stackoverflow.com/a/13229748/1810087) should `system("start \"\" \"c:\\Program Files\\Git\\bin\\sh.exe\" --login -i -c ..\\..\\");` should do... (or something similar with -c). – user1810087 Sep 13 '18 at 09:28
  • adding the -c ..\\..\\ just seems to close the window – Matt Jameson Sep 13 '18 at 09:33
  • No, but it does not do anything else: just open a shell, goes back two directories, closes the shell... what did you expect? – user1810087 Sep 13 '18 at 09:35
  • 3
    This smells like an [XY problem](http://mywiki.wooledge.org/XyProblem). – Biffen Sep 13 '18 at 09:36
  • if I run my code in the question it keeps the git bash window open – Matt Jameson Sep 13 '18 at 09:37

2 Answers2

2

assume you are on windows, start command can set working path with /D

start /D "./../.." "c:/Program Files/Git/in/sh.exe" --login -i
apple apple
  • 10,292
  • 2
  • 16
  • 36
0

Don't know if I understand correctly, but instead of launching just bash, why don't you launch from your C++ program a bash script; all the commands in the script will be executed.

system("/bin/bash -c myscript.sh");

Bash will be launched, but instead of a interactive shell, the commands in the script file myscript.sh will be executed.

However, I would use a different approach, rather than system(...). See the exec*(...) family of functions, and the fork() call. There are tons of pages where to look, and dozens of questions in this portal, as an example this question and answers.

J C Gonzalez
  • 861
  • 10
  • 23