Capturing mongo replica set state from mongo shell
The output you are trying to capture is the default prompt for the mongo shell in interactive mode.

As at MongoDB 4.0 there isn't a built-in helper to return replica set member status as a string, but you can derive the same status in JavaScript.

For example, create the following as getstate.js:

    var mystate = 'UNKNOWN';

    // Note: isMaster command does not require authentication
    var isMaster = db.isMaster();

    if (isMaster.msg == "isdbgrid") {
        mystate = "mongos";
    } else if (isMaster.ismaster &amp;&amp; !isMaster.setName) {
        mystate = 'STANDALONE';
    }

    if (isMaster.setName) {
        if (isMaster.secondary) {
            mystate = 'SECONDARY';
        } else if (isMaster.arbiterOnly) {
            mystate = "ARBITER";
        } else if (isMaster.primary === isMaster.me) {
            mystate = 'PRIMARY';
        }
    }

    print(mystate);


Now invoke mongo using --quiet to suppress any startup messages or warnings:

$ mongo localhost:27017 getstate.js --quiet
PRIMARY

$ mongo localhost:27018 getstate.js --quiet
SECONDARY

$ mongo localhost:27019 getstate.js --quiet
ARBITER