How can I edit a variable in a running shell?

Solution 1:

This can be done. Type var=$var and then expand and edit it. To expand, use Esc+Ctrle (the default shortcut, check output of bind -p | grep shell-expand-line to confirm).

So:

muru@muru-1604:~$ PS1=$PS1

will become:

muru@muru-1604:~$ PS1=${debian_chroot:+($debian_chroot)}\u@\h:\w\$

Which you can then edit in an editor with Ctrlx Ctrle (edit-and-execute-command in readline terms). When you save and quit, the saved content will be executed by the shell.

If you already have PS1=... in your history, you can just go back to that and Ctrlx Ctrle.

From the bash manual:

shell-expand-line (M-C-e)

Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions.

edit-and-execute-command (C-xC-e)

Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke $VISUAL, $EDITOR, and emacs as the editor, in that order.

Solution 2:

Instead of sourcing the bashrc, source another file, which just contains the variable.

  1. Create it:

    echo "PS1='$PS1'" > /tmp/PS1
    
    • Note: If the variable contains single quotes, you will need to use a command that can escape them, e.g.:

      declare -p PS1 | cut -d' ' -f3- > /tmp/PS1
      
  2. Open it in an editor, e.g. nano /tmp/PS1.

    • To avoid running nano over and over, you could run it in another terminal/TTY, or use a graphical editor.
  3. Make your changes and save.

  4. Source it:

    source /tmp/PS1
    
  5. Repeat steps 3 and 4 as needed.

Solution 3:

Zsh has a builtin called vared that lets you edit a variable inline. I wrote my own version, originally posted on Super User:

vared(){
    # Based on the zsh builtin of the same name.
    IFS= read -rei "${!1}" "$1"
}

Note this has some subtle differences from the Zsh builtin, e.g:

  • Won't error if the variable is unset
  • Checks the validity of the variable name before printing its value (e.g. vared $)
  • Truncates multi-line variables.

Then to edit the PS1, just run vared PS1.