Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What shell does std::system use?

TL;DR; I guess the shell that std::system use, is sh. But, I'm not sure.

I tried to print the shell, using this code: std::system("echo $SHELL"), and the output was /bin/bash. It was weird for me. So, I wanted to see, what happens if I do that in sh? And, the same output: /bin/bash. Also, if I use a command like SHELL="/usr/bin/something", to set the SHELL variable to another string, it will print the new string that I set to it (/usr/bin/something), and it looks it's not a good way to see what shell it's using. Then, I tried to check it, using the ps command, and the output was: bash, a.out, ps. It was weird to see bash in this list. So, I created a custom shell, and change the shell in gnome-terminal to it:

#include <iostream>

int main()
{
    std::string input;
    while (true)
    {
        std::string command;
        std::getline(std::cin, command);
        std::system(command.c_str());
    }
}

Now, it's easier to test, and I think, the results is better.

Then, I tried to test the ps command again, but in the custom shell, and the results was: test_shell, ps.

It was weird again. How the shell isn't sh, nor bash? And, the final test I did was: echo $0. And, the results was sh, in both custom shell, and normal program.

Edit

It seems like /bin/sh is linked to /bin/bash (ll /bin/sh command's output is /bin/sh -> bash), and actually, it seems like the only difference between sh and bash is filename, and the files's contents are the same. I checked the difference between these files with diff command too:

$ xxd /bin/sh > sh
$ xxd /bin/bash > bash
$ diff sh bash

(+ Yes, $SHELL doesn't means the running shell (I didn't know that when I was testing, and I just wanted to see what happens))

like image 975
NoIdeaForUsername Avatar asked Aug 12 '26 10:08

NoIdeaForUsername


2 Answers

The GNU sources (https://github.com/lattera/glibc/blob/master/sysdeps/posix/system.c) say

/bin/sh

So, whatever /bin/sh is hardlinked to is the shell invoked by std::system() on Linux.

(This is correct, as /bin/sh is expected to be linked to a sane shell capable of doing things with the system.)

like image 80
Dúthomhas Avatar answered Aug 14 '26 04:08

Dúthomhas


According to cppreference.com, std::system

calls the host environment's command processor (e.g. /bin/sh, cmd.exe, command.com)

This means the shell used will depend on the operating system.

On any POSIX OS (including Linux), the shell used by std::system is /bin/sh. (Though as the OP points out, /bin/sh could be a symlink to another shell.)

As for the SHELL environment variable, as has been pointed out in the comments, this environment variable cannot be used to reliably identify the running shell program. SHELL is defined by POSIX to

represent a pathname of the user's preferred command language interpreter

(source)

like image 23
Shane Bishop Avatar answered Aug 14 '26 03:08

Shane Bishop