2

When I am running an interactive bash session, I sometimes experiment with sh.

I call sh directly from this bash session.

My question is, how can I change the PS1 prompt of this subshell?

I would like the prompt to be something like sh$, notifying me that I am using sh and not bash.

What I have tried so far is:

  • I made a configuration file analogous to .bashrc named .shrc
  • I put only one line in it: export PS1='$(echo ${0})\$ '
  • I then modified ~/.profile to say the following:

    # if running bash
    if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
        if [ -f "$HOME/.bashrc" ]; then
            . "$HOME/.bashrc"
        fi
    # if running another shell
    else
        if [ -f "$HOME/.shrc" ]; then
            . "$HOME/.shrc"
        fi
    fi
    
  • I restarted the terminal, but the changes are not being applied.

  • If I run . ~/.shrc in sh manually, the changes do get applied.

What am I doing wrong?

1

It won't source that file by default. You can direct it to do so:

ENV=~/.shrc sh

Or you might add:

alias sh="PS1='\$0\$ ' sh" 

To your usual shell's environment file. It could simplify things.

Or even:

alias sh='ENV=~/.shrc sh'

Still, if you only want to declare the one variable for it, explicitly setting $PS1 on the command line like in the first alias example is probably the better way to go.

  • Nice solutions! What is going on with all the single apostrophes in alias sh='PS1='\''$0\$ '\'' sh'? – Stefan van den Akker Jul 30 '14 at 11:57
  • @Netfas - You can't put a hard quote within a hard-quoted string, but you can quote a hard quote though like "'" or \'. So what those do is close the current string like 'current string' wedges a backslash quoted hard quote in like \' then starts a new one like 'next string' - and they all get concatenated. 'string'\''string' – mikeserv Jul 30 '14 at 12:00
  • 1
    @Netfas - right $PS1 is special - it is evaled at each prompt. So you need the shell script in there, not the expansion of the variables. Especially since when you call it on the command line, it isn't even $0 yet - that's still bash at that time. If you do alias sh="PS1'$0\$ ' sh" - you're quoting the hardquotes - and $0 is expanded. But this would work: alias sh="PS1='\$0\$ ' sh". – mikeserv Jul 30 '14 at 12:12
  • 1
    @Netfas - actually, on second thought that's wrong - it's not about when you call it on the command line, it's about protecting $0 at alias definition time. Sorry about that. Anyway, the command still works, I just got ahead of myself I guess. And by the way, this makes for a pretty handy prompt in sh mode. – mikeserv Jul 30 '14 at 12:23
  • 1
    Awesome! I am definitely going to try that :) – Stefan van den Akker Jul 30 '14 at 12:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.