0

I'd like to have two commands - the first to short the prompt to $␣ or #␣. This should be permanent in the current shell, until I issue the command long_prompt to reset the prompt to the default version.

This is the short_prompt command script:

if [ $(id -u) = 0 ]; then
   PS1='\[\033[01;34m\]#\[\033[00m\] '
else
   PS1='\[\033[01;34m\]\$\[\033[00m\] '
fi

(As you see I honor the different prompts of admin shells and user shells)
When I source this script with like so:

$ . short_prompt

all works as expected, but for this I have to be in the directory where short_prompt resides or give the whole pathname, like so:

$ . /data/system/bin/short_prompt

I can't seem to figure out how to make this command accessible from anywhere (e.g. by creating a soft link to one of the path directories, e.g. /usr/local/bin) and type

$ short_prompt

or

$ long_prompt

I tried to add export in front of the two PS1='...' lines, but that did not work either.

  • 2
    Are you looking for ~/.bashrc? See the manual page of Bash. Define short_prompt and long_prompt as functions or aliases. – AlexP Jan 7 '18 at 0:25
  • OK, I will try that and report back... – wolfy Jan 7 '18 at 0:34
0

The only way to affect the PS1 of the running shell is to source the code.

There are many ways to solve this.

  1. Place one script in /home/user/bin

    Name a script short_prompt make it executable and place it in /home/user/bin.

    #!/bin/bash
    . /data/system/bin/short_prompt
    

    If you do so, the execution is simply:

    $ short_prompt

  2. Make an alias

    $ alias short_prompt='. /data/system/bin/short_prompt'
    

    Execute as:

    $ short_prompt
    
  3. Use ~/.bashrc:

    Place the code inside `~/.bashrc' as a function:

    short_prompt(){
        PS1='\[\033[01;34m\]\$\[\033[00m\] '
    }
    

    Call as:

     $ short_prompt
    
0

Put the scripts in a directory in your PATH, Bash's source uses it to look for the script to source. That can be changed with shopt sourcepath but it's on by default.

Another option is to make an alias or function to source the script from the path it lives in, or even put the whole prompt assignment in the function. That would also have the advantage that you wouldn't need to explicitly use . or source to call the script.

As an aside, \$ expands to # if you're root, so there's no need to set a separate path for root just for that.

What export does with the assignments is to make the environment variable visible to any further shells you might start under the current shell. Though with PS1 there's the problem that non-interactive shells will clear it, so it's usually reset in .bashrc.

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.