There are many useful tricks for the bash shell. This is how to show a count of all running jobs in the terminal.
Here are two ways to display the current number of jobs in your bash shell prompt:
1. Using the \j escape sequence:
PS1='\u@\h:\w \j\$ ' |
The /j escape sequence will show the jobs count.
Here’s what each part does:
\u
: Username@\h
: Hostname:\w
: Current working directory\j
: Number of background jobs\$
: Prompt symbol (usually $)
2. Conditional display with PROMPT_COMMAND:
This method allows you to only show the job count if any jobs are running. Add the following lines to your ~/.bashrc
file:
PROMPT_COMMAND='hasjobs=$(jobs -p)' PS1='${hasjobs:+\j }\$ ' |
Here, the PROMPT_COMMAND
variable runs the jobs -p
command before displaying the prompt. If any jobs are found, the hasjobs
variable will be non-empty, and the \j
escape sequence will be displayed.
You have several options to show different prompts based on an SSH connection:
1. Using $SSH_TTY
variable:
- This checks if a terminal is allocated for the session. It’s typically set for interactive SSH sessions but not for script execution via SSH.
- Add the following lines to your
~/.bashrc
file:
if [[ -n "$SSH_TTY" ]]; then PS1='SSH:\u@\h:\w\$ ' else PS1='\u@\h:\w\$ ' fi |
- This sets a different prompt with “SSH:” prefix when connected via SSH and a regular prompt otherwise.
2. Checking $TERM
variable:
- This variable holds the terminal type being used. Specific values like “dumb” or “xterm” might indicate non-interactive sessions.
- Add the following lines to your
~/.bashrc
file:
if [[ "$TERM" =~ ^(dumb|xterm)$ ]]; then PS1='\u@\h:\w\$ ' else PS1='SSH:\u@\h:\w\$ ' fi |
- This sets the SSH prompt only if the terminal type suggests a non-interactive session.
3. Using ps1_ssh()
function:
- This method allows more complex logic and customization.
- Add the following code to your
~/.bashrc
file:
ps1_ssh() { if [[ -n "$SSH_TTY" ]]; then echo "SSH: \u@\h:\w" else echo "\u@\h:\w" fi } # Set the prompt function PS1="$(ps1_ssh)$ " |
- This defines a function
ps1_ssh
that checks for SSH connection and returns the desired prompt. Then, it sets thePS1
variable to the output of this function.
4. Using shell configuration files on remote servers:
- If you want to customize the prompt on remote servers where you connect via SSH, you can edit the configuration files like
.bashrc
or.zshrc
on those servers. - This allows you to set different prompts specifically for users connecting via SSH.