Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I open bash from a popen() stream?

According to the man page for popen() I am opening a /bin/sh...Is there a way I can overload this behavior to open a /bin/bash shell and interact with BASH shell scripts? Or do I need to open a pty style connection to do that?

like image 829
Jeff Zacher Avatar asked Oct 23 '22 11:10

Jeff Zacher


1 Answers

If you want to use bash constructs in the snippet you pass to popen, you can call bash explicitly from sh.

f = popen("exec bash -c 'shopt -s dotglob; cat -- *'", "r");

If you need single quotes inside the bash snippet, pass them as '\''. All other characters are passed literally.

If you have an existing bash script that you want to run, simply specify its path, same as any script or other program. Make sure that the script is executable and begins with #!/usr/bin/env bash or #!/bin/bash. If you have a script that may be non-executable (for example because of Windows portability constraints), you can invoke bash explicitly:

f = popen("exec bash myscript.bash", "r");

Alternatively, write your own custom popen-like function that calls the program you want (but do that only if simpler solutions are not satisfactory, because it's more difficult to get right). See e.g. popen() alternative.

like image 193
Gilles 'SO- stop being evil' Avatar answered Oct 27 '22 01:10

Gilles 'SO- stop being evil'