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?
-
Remember that on most Linux systems `/bin/sh` is symlinked to `/bin/bash`. – Some programmer dude Sep 03 '12 at 09:35
-
2Most? Maybe but not on Ubuntu. – Prof. Falken Sep 03 '12 at 09:36
-
@JoachimPileborg Yes but it has different behavior when invoked as `sh`. – hamstergene Sep 03 '12 at 09:37
2 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.

- 1
- 1

- 104,111
- 38
- 209
- 254
-
That is just what I need to know. Thanks!!! Also a link in your example link lead me to a jacket for spawning a process that is in GLIB. I think this is exactly what I need... – Jeff Zacher Sep 06 '12 at 22:05
Probably the simplest is to have a small sh script which in turn invokes your bash script like so:
#!/bin/sh
exec bash yourscript.sh "$@"
Or you can forgo popen and implement your own popen with fork() and execl().

- 104,111
- 38
- 209
- 254

- 24,226
- 19
- 100
- 173
-
A separate sh script is useless. You might as well call `popen` on the bash script directly. – Gilles 'SO- stop being evil' Sep 05 '12 at 01:11
-
Useless, I think is a bit much. Convoluted yes, but it would work. +1 to your answer, though. And thanks for the edit. – Prof. Falken Sep 05 '12 at 05:03