|
Home | Switchboard | Unix Administration | Red Hat | TCP/IP Networks | Neoliberalism | Toxic Managers |
(slightly skeptical) Educational society promoting "Back to basics" movement against IT overcomplexity and bastardization of classic Unix |
|
|
Shell prompts are useful tools that simplify life of sysadmins and regular users alike, if set correctly. They became an esoteric art in bash as bash has special macros for PS1-PS4 that simplify construction of complex shells. Unfortunately not many of those esoteric examples are useful.
The main problems with displaying full directory in bash prompts is that if we are somewhere deep
in filesystem and the path is long it became less usable. This happens if you use some \h:\w\$
for PS1
string. The \w
escape character expands to
the user's current working directory. If nesting is deep
prompt occupy almost all command line. In Bash version 4.0 or above (check with
bash --version ), you can set the PROMPT_DIRTRIM variable for the
shell. This limits the length of the tail end of the \w expansion to the specified number of path elements. For example
PROMPT_DIRTRIM=3
This is a good thing to include in your ~/.bash_profile
file (and probably in
/etc/profile so that all user enjoy this behnefit, unless they define thier own prompts), if you often find yourself
deep in directory trees where the upper end of the hierarchy isn't of immediate interest to you. You
can remove the effect again by unsetting the variable:
unset PROMPT_DIRTRIM
In bash 3.x and older you can display two last directories by using:
export PS1='\u@\h:${PWD##/*/*}${PWD#${PWD%/*/*}} # '
represents an improvement as it both current and parent directory are displayed instead of just current, which is not really useful.
Another approach is to program switch printing the path of a separate line if length of the $CWD is longer then say 20 characters.
There is also widespread perversions in a forms of esoteric colorizing schemes. Some minimal coloring is useful:
So please do not spend much time inventing a new super coloring scheme for your prompts (some people have spent months trying various combination of colors for different hosts ;-). This is a road to nowhere/
Classic Unix prompt also look differently for root and regular users and that should be preserved:
regular users : username@hostname:/path $
root: hostname:/path#
When customizing bash prompt you can operate on three levels:
There are multiple web pages with examples of bash prompts. Some of them are pretty educational
The most important rule in customizing bash prompt is "Not to much zeal" ;-).
NOTE: In bash 4 macro \w also performs home directory folding to the specified level via PROMPT_DIRTRIM variable |
The following escape codes between \[\e[
and m\] are recognized
in text:
Black | 0;30 |
Dark Gray | 1;30 |
Blue | 0;34 |
Light Blue | 1;34 |
Green | 0;32 |
Light Green | 1;32 |
Cyan | 0;36 |
Light Cyan | 1;36 |
Red | 0;31 |
Light Red | 1;31 |
Purple | 0;35 |
Light Purple | 1;35 |
Brown | 0;33 |
Yellow | 1;33 |
Light Gray | 0;37 |
White | 1;37 |
For example you can try the following ;-)
export PS1="\[\e[36;1m\] \[\e[31;1m\]\u\[\033[0m\]@\[\e[34;1m\]\h\[\e[0;30m\] $ "
PROMPT_COMMAND
If set, the value is interpreted as a command to execute before the printing of each primary prompt ($PS1).
PROMPT_COMMAND usually call a function that can contain ordinary bash statements whereas the PS1 is limited to env variables and the special characters, such as '\h' for hostname. For excample
function prompt_command {
export PS1=$(~/bin/bash_prompt)
}
export PROMPT_COMMAND=prompt_command
Here is a relevant quote from Bash Prompt HOWTO:
Bash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.
[21:55:01][giles@nikola:~] PS1="[\u@\h:\w]\$ " [giles@nikola:~] PROMPT_COMMAND="date +%H%M" 2155 [giles@nikola:~] d bin mail 2156 [giles@nikola:~]What happened above was that I changed PS1 to no longer include the \t escape sequence (added in a previous section), so the time was no longer a part of the prompt. Then I used date +%H%M to display the time in a format I like better. But it appears on a different line than the prompt. Tidying this up using echo -n ... as shown below works with Bash 2.0+, but appears not to work with Bash 1.14.7: apparently the prompt is drawn in a different way, and the following method results in overlapping text.
2156 [giles@nikola:~] PROMPT_COMMAND="echo -n [$(date +%H%M)]" [2156][giles@nikola:~]$ [2156][giles@nikola:~]$ d bin mail [2157][giles@nikola:~]$ unset PROMPT_COMMAND [giles@nikola:~]echo -n ... controls the output of the date command and suppresses the trailing newline, allowing the prompt to appear all on one line. At the end, I used the unset command to remove the PROMPT_COMMAND environment variable.
ksh shell does not have macros for prompt so you need to script a usable prompt. For Solaris a very simplistic one might look like:
case `/usr/xpg4/bin/id -u` in 0) PS1=" [1m [31m\$HOST:\$PWD\# [0m" ;; *) PS1="\$LOGNAME\@\$HOST:\$PWD\$ " ;; esac PS2='>' export PS1 PS2
In BASH it's simpler generate # for root: \$ is a bash prompt macro that expands to # if the effective UID is 0, and to $ otherwise. That means that equivalent Bash prompt (but without color scheme) can look something like
PS1="\u@\h:\w\ \\$ "
\w also performs directory folding in bash.
In ksh93 you can try to to truncate the prompt in case the current directory is a subdirectory of
the home directory. ksh93 introduced ${parameter/pattern/string}
substitution which later was replicated by BASH and that can be used for kind of directory folding like
in the following example:
PS1='$LOGNAME\@\$HOST:\$PWD\${PWD#$OLDPWD/}$ '
Here are relevant quotes from ksh93 and bash documentation:
ksh93:
${parameter /pattern /string }
${parameter //pattern /string }
${parameter /#pattern /string } If pattern begins with `#', it must match at the beginning of the expanded value of parameter
${parameter /%pattern /string }
Expands parameter and replaces the longest match of pattern with the given string. Each occurrence of \n in string is replaced by the portion of parameter that matches the n -th sub-pattern. In the first form, only the first occurrence of pattern is replaced. In the second form, each match for pattern is replaced by the given string. The third form restricts the pattern match to the beginning of the string while the fourth form restricts the pattern match to the end of the string. When string is null, the pattern will be deleted and the / in front of string may be omitted. When parameter is @, *, or an array variable with subscript @ or *, the substitution operation is applied to each element in turn.
bash:
${parameter//pattern/string}
The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. In the first form, only the first match is replaced. The second form causes all matches of pattern to be replaced with string. If pattern begins with `#', it must match at the beginning of the expanded value of parameter. If pattern begins with `%', it must match at the end of the expanded value of parameter. If string is null, matches of pattern are deleted and the /
following pattern may be omitted. If parameter is `@' or `*', the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with `@' or `*', the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list.
But the problem is that slashes as $HOME expansion are interpreted as substitution delimiter ("/") so the following idea does not work (Solaris example follows):
case `/usr/xpg4/bin/id -u` in 0) PS1=" [1m [31m\$LOGNAME\@\$HOST:\${PWD/#$HOME/~}\# [0m" ;; *) PS1="\$LOGNAME\@\$HOST:\${PWD/#$HOME/~}\$ " ;; esac PS2='>' export PS1 PS2
Paradoxically the following works correctly but it just delete home directory without substitution so it not very useful:
case `/usr/xpg4/bin/id -u` in 0) PS1=" [1m [31m\$LOGNAME\@\$HOST:\${PWD#$HOME}\# [0m" ;; *) PS1="\$LOGNAME\@\$HOST:\${PWD#$HOME}\$ " ;; esac PS2='>' export PS1 PS2
Good luck with your own ksh93 shell prompt experiments and write me if you manage to do this trick in ksh93 correctly !
Dr. Nikolai Bezroukov
|
Switchboard | ||||
Latest | |||||
Past week | |||||
Past month |
Nov 08, 2019 | opensource.com
Your Linux terminal probably supports Unicode, so why not take advantage of that and add a seasonal touch to your prompt? 11 Dec 2018 Jason Baker (Red Hat) Feed 84 up 3 comments Image credits : Jason Baker x Subscribe now
Get the highlights in your inbox every week.
https://opensource.com/eloqua-embedded-email-capture-block.html?offer_id=70160000000QzXNAA0
- Top 7 terminal emulators for Linux
- 10 command-line tools for data analysis in Linux
- Download Now: SSH cheat sheet
- Advanced Linux commands cheat sheet
- Linux command line tutorials
Hello once again for another installment of the Linux command-line toys advent calendar. If this is your first visit to the series, you might be asking yourself what a command-line toy even is? Really, we're keeping it pretty open-ended: It's anything that's a fun diversion at the terminal, and we're giving bonus points for anything holiday-themed.
Maybe you've seen some of these before, maybe you haven't. Either way, we hope you have fun.
Today's toy is super-simple: It's your Bash prompt. Your Bash prompt? Yep! We've got a few more weeks of the holiday season left to stare at it, and even more weeks of winter here in the northern hemisphere, so why not have some fun with it.
Your Bash prompt currently might be a simple dollar sign ( $ ), or more likely, it's something a little longer. If you're not sure what makes up your Bash prompt right now, you can find it in an environment variable called $PS1. To see it, type:
echo $PS1For me, this returns:
[\u@\h \W]\$The \u , \h , and \W are special characters for username, hostname, and working directory. There are others you can use as well; for help building out your Bash prompt, you can use EzPrompt , an online generator of PS1 configurations that includes lots of options including date and time, Git status, and more.
You may have other variables that make up your Bash prompt set as well; $PS2 for me contains the closing brace of my command prompt. See this article for more information.
To change your prompt, simply set the environment variable in your terminal like this:
$ PS1 = '\u is cold: '
jehb is cold:To set it permanently, add the same code to your /etc/bashrc using your favorite text editor.
So what does this have to do with winterization? Well, chances are on a modern machine, your terminal support Unicode, so you're not limited to the standard ASCII character set. You can use any emoji that's a part of the Unicode specification, including a snowflake ❄, a snowman ☃, or a pair of skis 🎿. You've got plenty of wintery options to choose from.
🎄 Christmas Tree
🧥 Coat
🦌 Deer
🧤 Gloves
🤶 Mrs. Claus
🎅 Santa Claus
🧣 Scarf
🎿 Skis
🏂 Snowboarder
❄ Snowflake
☃ Snowman
⛄ Snowman Without Snow
🎁 Wrapped GiftPick your favorite, and enjoy some winter cheer. Fun fact: modern filesystems also support Unicode characters in their filenames, meaning you can technically name your next program "❄❄❄❄❄.py" . That said, please don't.
Do you have a favorite command-line toy that you think I ought to include? The calendar for this series is mostly filled out but I've got a few spots left. Let me know in the comments below, and I'll check it out. If there's space, I'll try to include it. If not, but I get some good submissions, I'll do a round-up of honorable mentions at the end.
Jun 29, 2014 | access.redhat.com
Raw
- The shell prompt is controlled via the PS environment variables.
**PS1** - The value of this parameter is expanded and used as the primary prompt string. The default value is \u@\h \W\\$ . **PS2** - The value of this parameter is expanded as with PS1 and used as the secondary prompt string. The default is ] **PS3** - The value of this parameter is used as the prompt for the select command **PS4** - The value of this parameter is expanded as with PS1 and the value is printed before each command bash displays during an execution trace. The first character of PS4 is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is +Raw
PS1
is a primary prompt variable which holds\u@\h \W\\$
special bash characters. This is the default structure of the bash prompt and is displayed every time a user logs in using a terminal. These default values are set in the/etc/bashrc
file.- The special characters in the default prompt are as follows:
\u = username \h = hostname \W = current working directoryRaw
- This command will show the current value.
# echo $PS1Raw
- This can be modified by changing the PS1 variable:
# PS1='[[prod]\u@\h \W]\$'Raw
- The modified shell prompt will look like:
[[prod]root@hostname ~]#
- In order to make these settings permanent, edit the
/etc/bashrc
file:Find this line:
Raw[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ "And change it as needed:
Raw[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[[prod]\u@\h \W]\\$ "
- Product(s)
- Red Hat Enterprise Linux
- Component
- bash
- Category
- Customize or extend
This solution is part of Red Hat's fast-track publication program, providing a huge library of solutions that Red Hat engineers have created while supporting our customers. To give you the knowledge you need the instant it becomes available, these articles may be presented in a raw and unedited form. 2 Comments Log in to comment
MW Community Member 48 points
6 October 2016 1:53 PM Mike Willis
27 March 2019 12:44 PM Mike ChanslorThis solution has simply "Red Hat Enterprise Linux" in the Environment section implying it applies to all versions of Red Hat Enterprise Linux.
Editing /etc/bashrc is against the advice of the comments in /etc/bashrc on Red Hat Enterprise Linux 7 which say
Raw# It's NOT a good idea to change this file unless you know what you # are doing. It's much better to create a custom.sh shell script in # /etc/profile.d/ to make custom changes to your environment, as this # will prevent the need for merging in future updates.On RHEL 7 instead of the solution suggested above create a /etc/profile.d/custom.sh which contains
RawPS1="[[prod]\u@\h \W]\\$ "Hello Red Hat community! I also found this useful: Raw
Special prompt variable characters: \d The date, in "Weekday Month Date" format (e.g., "Tue May 26"). \h The hostname, up to the first . (e.g. deckard) \H The hostname. (e.g. deckard.SS64.com) \j The number of jobs currently managed by the shell. \l The basename of the shell's terminal device name. \s The name of the shell, the basename of $0 (the portion following the final slash). \t The time, in 24-hour HH:MM:SS format. \T The time, in 12-hour HH:MM:SS format. \@ The time, in 12-hour am/pm format. \u The username of the current user. \v The version of Bash (e.g., 2.00) \V The release of Bash, version + patchlevel (e.g., 2.00.0) \w The current working directory. \W The basename of $PWD. \! The history number of this command. \# The command number of this command. \$ If you are not root, inserts a "$"; if you are root, you get a "#" (root uid = 0) \nnn The character whose ASCII code is the octal value nnn. \n A newline. \r A carriage return. \e An escape character (typically a color code). \a A bell character. \\ A backslash. \[ Begin a sequence of non-printing characters. (like color escape sequences). This allows bash to calculate word wrapping correctly. \] End a sequence of non-printing characters. Using single quotes instead of double quotes when exporting your PS variables is recommended, it makes the prompt a tiny bit faster to evaluate plus you can then do an echo $PS1 to see the current prompt settings.
Nov 08, 2019 | stackoverflow.com
How to escape unicode characters in bash prompt correctly Ask Question Asked 8 years, 2 months ago Active 9 months ago Viewed 6k times 7 2
Andy Ray ,Aug 18, 2011 at 19:08
I have a specific method for my bash prompt, let's say it looks like this:CHAR="༇ " my_function=" prompt=\" \[\$CHAR\]\" echo -e \$prompt" PS1="\$(${my_function}) \$ "To explain the above, I'm builidng my bash prompt by executing a function stored in a string, which was a decision made as the result of this question . Let's pretend like it works fine, because it does, except when unicode characters get involved
I am trying to find the proper way to escape a unicode character, because right now it messes with the bash line length. An easy way to test if it's broken is to type a long command, execute it, press CTRL-R and type to find it, and then pressing CTRL-A CTRL-E to jump to the beginning / end of the line. If the text gets garbled then it's not working.
I have tried several things to properly escape the unicode character in the function string, but nothing seems to be working.
Special characters like this work:
COLOR_BLUE=$(tput sgr0 && tput setaf 6) my_function=" prompt="\\[\$COLOR_BLUE\\] \" echo -e \$prompt"Which is the main reason I made the prompt a function string. That escape sequence does NOT mess with the line length, it's just the unicode character.
Andy Ray ,Aug 23, 2011 at 2:09
The\[...\]
sequence says to ignore this part of the string completely, which is useful when your prompt contains a zero-length sequence, such as a control sequence which changes the text color or the title bar, say. But in this case, you are printing a character, so the length of it is not zero. Perhaps you could work around this by, say, using a no-op escape sequence to fool Bash into calculating the correct line length, but it sounds like that way lies madness.The correct solution would be for the line length calculations in Bash to correctly grok UTF-8 (or whichever Unicode encoding it is that you are using). Uhm, have you tried without the
\[...\]
sequence?Edit: The following implements the solution I propose in the comments below. The cursor position is saved, then two spaces are printed, outside of
\[...\]
, then the cursor position is restored, and the Unicode character is printed on top of the two spaces. This assumes a fixed font width, with double width for the Unicode character.PS1='\['"`tput sc`"'\] \['"`tput rc`"'༇ \] \$ 'At least in the OSX Terminal, Bash 3.2.17(1)-release, this passes cursory [sic] testing.
In the interest of transparency and legibility, I have ignored the requirement to have the prompt's functionality inside a function, and the color coding; this just changes the prompt to the character, space, dollar prompt, space. Adapt to suit your somewhat more complex needs.
tripleee ,Aug 23, 2011 at 7:01
@tripleee wins it, posting the final solution here because it's a pain to post code in comments:CHAR="༇" my_function=" prompt=\" \\[`tput sc`\\] \\[`tput rc`\\]\\[\$CHAR\\] \" echo -e \$prompt" PS1="\$(${my_function}) \$ "The trick as pointed out in @tripleee's link is the use of the commands
tput sc
andtput rc
which save and then restore the cursor position. The code is effectively saving the cursor position, printing two spaces for width, restoring the cursor position to before the spaces, then printing the special character so that the width of the line is from the two spaces, not the character.> ,
(Not the answer to your problem, but some pointers and general experience related to your issue.)I see the behaviour you describe about cmd-line editing (Ctrl-R, ... Cntrl-A Ctrl-E ...) all the time, even without unicode chars.
At one work-site, I spent the time to figure out the diff between the terminals interpretation of the TERM setting VS the TERM definition used by the OS (well, stty I suppose).
NOW, when I have this problem, I escape out of my current attempt to edit the line, bring the line up again, and then immediately go to the 'vi' mode, which opens the vi editor. (press just the 'v' char, right?). All the ease of use of a full-fledged session of vi; why go with less ;-)?
Looking again at your problem description, when you say
my_function=" prompt=\" \[\$CHAR\]\" echo -e \$prompt"That is just a string definition, right? and I'm assuming your simplifying the problem definition by assuming this is the output of your
my_function
. It seems very likely in the steps of creating the function definition, calling the function AND using the values returned are a lot of opportunities for shell-quoting to not work the way you want it to.If you edit your question to include the
my_function
definition, and its complete use (reducing your function to just what is causing the problem), it may be easier for others to help with this too. Finally, do you useset -vx
regularly? It can help show how/wnen/what of variable expansions, you may find something there.Failing all of those, look at Orielly termcap & terminfo . You may need to look at the man page for your local systems
stty
and related cmds AND you may do well to look for user groups specific to you Linux system (I'm assuming you use a Linux variant).I hope this helps.
flowblok's blog
that diagram shows what happens according to the man page, and not what happens when you actually try it out in real life. This second diagram more accurately captures the insanity of bash:See how remote interactive login shells read /etc/bash.bashrc, but normal interactive login shells don't? Sigh.
Finally, here's a repository containing my implementation and the graphviz files for the above diagram. If your POSIX-compliant shell isn't listed here, or if I've made a horrible mistake (or just a tiny one), please send me a pull request or make a comment below, and I'll update this post accordingly.
[1]and since I'm writing this, I can make you say whatever I want for the purposes of narrative.
Jan 26, 2019 | flowblok.id.au
Adrian • a month ago ,
6 years late, but...
In my experience, if your bash sources /etc/bash.bashrc, odds are good it also sources /etc/bash.bash_logout or something similar on logout (after ~/.bash_logout, of course).
From bash-4.4/config-top.h:
/* System-wide .bashrc file for interactive shells. */ /* #define SYS_BASHRC "/etc/bash.bashrc" */ /* System-wide .bash_logout for login shells. */ /* #define SYS_BASH_LOGOUT "/etc/bash.bash_logout" */(Yes, they're disabled by default.)
Check the FILES section of your system's bash man page for details.
Dec 20, 2018 | forums.debian.net
pawRoot " 2018-10-15 17:13
Just spent some time editing .bashrc to make my life easier, and wondering if anyone has some cool "tricks" for bash as well.Here is mine:
- Code: Select all
# changing shell appearance
PS1='\[\033[0;32m\]\[\033[0m\033[0;32m\]\u\[\033[0;36m\] @ \[\033[0;36m\]\h \w\[\033[0;32m\]$(__git_ps1)\n\[\033[0;32m\]└─\[\033[0m\033[0;32m\] \$\[\033[0m\033[0;32m\] ▶\[\033[0m\] '
# aliases
alias la="ls -la --group-directories-first --color"
# clear terminal
alias cls="clear"
#
alias sup="sudo apt update && sudo apt upgrade"
# search for package
alias apts='apt-cache search'
# start x session
alias x="startx"
# download mp3 in best quality from YouTube
# usage: ytmp3 https://www.youtube.com/watch?v=LINK
alias ytmp3="youtube-dl -f bestaudio --extract-audio --audio-format mp3 --audio-quality 0"
# perform 'la' after 'cd'
alias cd="listDir"
listDir() {
builtin cd "$*"
RESULT=$?
if [ "$RESULT" -eq 0 ]; then
la
fi
}
# type "extract filename" to extract the file
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xvjf $1 ;;
*.tar.gz) tar xvzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xvf $1 ;;
*.tbz2) tar xvjf $1 ;;
*.tgz) tar xvzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "don't know how to extract '$1'..." ;;
esac
else
echo "'$1' is not a valid file!"
fi
}
# obvious one
alias ..="cd .."
alias ...="cd ../.."
alias ....="cd ../../.."
alias .....="cd ../../../.."
# tail all logs in /var/log
alias logs="find /var/log -type f -exec file {} \; | grep 'text' | cut -d' ' -f1 | sed -e's/:$//g' | grep -v '[0-9]$' | xargs tail -f"
Head_on_a_Stick " 2018-10-15 18:11
pawRoot wrote:Erm, did you know that `tar` autoextracts these days? This will work for pretty much anything:
- Code: Select all
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xvjf $1 ;;
*.tar.gz) tar xvzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar x $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xvf $1 ;;
*.tbz2) tar xvjf $1 ;;
*.tgz) tar xvzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "don't know how to extract '$1'..." ;;
esac
else
echo "'$1' is not a valid file!"
fi
}
I have these functions in my .mkshrc (bash is bloat!):
- Code: Select all
tar xf whatever.tar.whatever
The mnt function acts like a poor person's arch-chroot and will bind mount /proc /sys & /dev before chrooting then tear it down afterwards.
- Code: Select all
function mnt {
for i in proc sys dev dev/pts; do sudo mount --bind /$i "$1"$i; done &
sudo chroot "$1" /bin/bash
sudo umount -R "$1"{proc,sys,dev}
}
function mkiso {
xorriso -as mkisofs \
-iso-level 3 \
-full-iso9660-filenames \
-volid SharpBang-stretch \
-eltorito-boot isolinux/isolinux.bin \
-eltorito-catalog isolinux/boot.cat \
-no-emul-boot -boot-load-size 4 -boot-info-table \
-isohybrid-mbr isolinux/isohdpfx.bin \
-eltorito-alt-boot \
-e boot/grub/efi.img \
-no-emul-boot -isohybrid-gpt-basdat \
-output ../"$1" ./
}The mkiso function builds a UEFI-capable Debian live system (with the name of the image given as the first argument).
The only other stuff I have are aliases, not really worth posting.
dbruce wrote: Ubuntu forums try to be like a coffee shop in Seattle. Debian forums strive for the charm and ambience of a skinhead bar in Bacau. We intend to keep it that way.pawRoot " 2018-10-15 18:23
Head_on_a_Stick wrote: Erm, did you know that `tar` autoextracts these days? This will work for pretty much anything:But it won't work for zip or rar right ?
None1975 " 2018-10-16 13:02
Here is compilation of cool "tricks" for bash. This is similar to oh-my-zsh. OS: Debian Stretch / WM : Fluxbox
Debian Wiki | DontBreakDebian , My config files in github
debiman " 2018-10-21 14:38
i have a LOT of stuff in my /etc/bash.bashrc, because i want it to be available for the root user too.
i won't post everything, but here's a "best of" from both /etc/bash.bashrc and ~/.bashrc:
- Code: Select all
case ${TERM} in
xterm*|rxvt*|Eterm|aterm|kterm|gnome*)
PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND; }'printf "\033]0;%s: %s\007" "${SHELL##*/}" "${PWD/#$HOME/\~}"'
;;
screen)
PROMPT_COMMAND=${PROMPT_COMMAND:+$PROMPT_COMMAND; }'printf "\033_%s@%s:%s\033\\" "${USER}" "${HOSTNAME%%.*}" "${PWD/#$HOME/\~}"'
;;
linux)
setterm --blength 0
setterm --blank 4
setterm --powerdown 8
;;
esac
PS2='cont> '
PS3='Choice: '
PS4='DEBUG: '
# Bash won't get SIGWINCH if another process is in the foreground.
# Enable checkwinsize so that bash will check the terminal size when
# it regains control.
# http://cnswww.cns.cwru.edu/~chet/bash/FAQ (E11)
shopt -s checkwinsize
# forums.bunsenlabs.org/viewtopic.php?pid=27494#p27494
# also see aliases '...' and '....'
shopt -s autocd
# opensource.com/article/18/5/bash-tricks
shopt -s cdspell
# as big as possible!!!
HISTSIZE=500000
HISTFILESIZE=2000000
# unix.stackexchange.com/a/18443
# history: erase duplicates...
HISTCONTROL=ignoredups:erasedups
shopt -s histappend
# next: enables usage of CTRL-S (backward search) with CTRL-R (forward search)
# digitalocean.com/community/tutorials/how-to-use-bash-history-commands-and-expansions-on-a-linux-vps#searching-through-bash-history
stty -ixon
if [[ ${EUID} == 0 ]] ; then
# root = color=1 # red
if [ "$TERM" != "linux" ]; then
PS1="\[$(tput setaf 1)\]\[$(tput rev)\] \[$(tput sgr0)\]\[$(tput setaf 5)\]\${?#0}\[$(tput setaf 1)\] \u@\h \w\[$(tput sgr0)\]\n\[$(tput rev)\] \[$(tput sgr0)\] "
else
# adding \t = time to tty prompt
PS1="\[$(tput setaf 1)\]\[$(tput rev)\] \[$(tput sgr0)\]\[$(tput setaf 5)\]\${?#0}\[$(tput setaf 1)\] \t \u@\h \w\[$(tput sgr0)\]\n\[$(tput rev)\] \[$(tput sgr0)\] "
fi
else
if [ "$TERM" != "linux" ]; then
PS1="\[$(tput setaf 2)\]\[$(tput rev)\] \[$(tput sgr0)\]\[$(tput setaf 5)\]\${?#0}\[$(tput setaf 2)\] \u@\h \w\[$(tput sgr0)\]\n\[$(tput rev)\] \[$(tput sgr0)\] "
else
# adding \t = time to tty prompt
PS1="\[$(tput setaf 2)\]\[$(tput rev)\] \[$(tput sgr0)\]\[$(tput setaf 5)\]\${?#0}\[$(tput setaf 2)\] \t \u@\h \w\[$(tput sgr0)\]\n\[$(tput rev)\] \[$(tput sgr0)\] "
fi
fi
[ -r /usr/share/bash-completion/bash_completion ] && . /usr/share/bash-completion/bash_completion || true
export EDITOR="nano"
man() {
env LESS_TERMCAP_mb=$(printf "\e[1;31m") \
LESS_TERMCAP_md=$(printf "\e[1;31m") \
LESS_TERMCAP_me=$(printf "\e[0m") \
LESS_TERMCAP_se=$(printf "\e[0m") \
LESS_TERMCAP_so=$(printf "\e[7m") \
LESS_TERMCAP_ue=$(printf "\e[0m") \
LESS_TERMCAP_us=$(printf "\e[1;32m") \
man "$@"
}
#LESS_TERMCAP_so=$(printf "\e[1;44;33m")
# that used to be in the man function for less's annoyingly over-colorful status line.
# changed it to simple reverse video (tput rev)
alias ls='ls --group-directories-first -hF --color=auto'
alias ll='ls --group-directories-first -hF --color=auto -la'
alias mpf='/usr/bin/ls -1 | mpv --playlist=-'
alias ruler='slop -o -c 1,0.3,0'
alias xmeasure='slop -o -c 1,0.3,0'
alias obxprop='obxprop | grep -v _NET_WM_ICON'
alias sx='exec startx > ~/.local/share/xorg/xlog 2>&1'
alias pngq='pngquant --nofs --speed 1 --skip-if-larger --strip '
alias screencap='ffmpeg -r 15 -s 1680x1050 -f x11grab -i :0.0 -vcodec msmpeg4v2 -qscale 2'
alias su='su -'
alias fblc='fluxbox -list-commands | column'
alias torrench='torrench -t -k -s -x -r -l -i -b --sorted'
alias F5='while sleep 60; do notify-send -u low "Pressed F5 on:" "$(xdotool getwindowname $(xdotool getwindowfocus))"; xdotool key F5; done'
alias aurs='aurman --sort_by_name -Ss'
alias cal3='cal -3 -m -w --color'
alias mkdir='mkdir -p -v'
alias ping='ping -c 5'
alias cd..='cd ..'
alias off='systemctl poweroff'
alias xg='xgamma -gamma'
alias find='find 2>/dev/null'
alias stressme='stress --cpu 8 --io 4 --vm 2 --vm-bytes 128M --timeout'
alias hf='history|grep'
alias du1='du -m --max-depth=1|sort -g|sed "s/\t./M\t/g ; s/\///g"'
alias zipcat='gunzip -c'
mkcd() {
mkdir -p "$1"
echo cd "$1"
cd "$1"
}
Nov 07, 2014 | sanctum.geek.nz
The common default of some variant of
\h:\w\$
for a Bash promptPS1
string includes the\w
escape character, so that the user's current working directory appears in the prompt, but with$HOME
shortened to a tilde:tom@sanctum:~$ tom@sanctum:~/Documents$ tom@sanctum:/usr/local/nagios$This is normally very helpful, particularly if you leave your shell for a time and forget where you are, though of course you can always call the
pwd
shell builtin. However it can get annoying for very deep directory hierarchies, particularly if you're using a smaller terminal window:tom@sanctum:/chroot/apache/usr/local/perl/app-library/lib/App/Library/Class:~$If you're using Bash version 4.0 or above (
bash --version
), you can save a bit of terminal space by setting thePROMPT_DIRTRIM
variable for the shell. This limits the length of the tail end of the\w
and\W
expansions to that number of path elements:tom@sanctum:/chroot/apache/usr/local/app-library/lib/App/Library/Class$ PROMPT_DIRTRIM=3 tom@sanctum:.../App/Library/Class$This is a good thing to include in your
~/.bashrc
file if you often find yourself deep in directory trees where the upper end of the hierarchy isn't of immediate interest to you. You can remove the effect again by unsetting the variable:tom@sanctum:.../App/Library/Class$ unset PROMPT_DIRTRIM tom@sanctum:/chroot/apache/usr/local/app-library/lib/App/Library/Class$
Jul 07, 2017 | opensource.com
7 comments your Bash prompt.Anyone who has started a terminal in Linux is familiar with the default Bash prompt:
[ user @ $host ~ ] $
But did you know is that this is completely customizable and can contain some very useful information? Here are a few hidden treasures you can use to customize your Bash prompt.
How is the Bash prompt set?The Bash prompt is set by the environment variable PS1 (Prompt String 1), which is used for interactive shell prompts. There is also a PS2 variable, which is used when more input is required to complete a Bash command.
[ dneary @ dhcp- 41 - 137 ~ ] $ export PS1 = "[Linux Rulez]$ "
[ Linux Rulez ] export PS2 = "... "
[ Linux Rulez ] if true ; then
... echo "Success!"
... fi
Success ! Where is the value of PS1 set?PS1 is a regular environment variable.
The system default value is set in /etc/bashrc . On my system, the default prompt is set with this line:
[ " $PS1 " = "\\s-\ \v \\ \$ " ] && PS1 = "[\u@\h \W]\ \$ "
This tests whether the value of PS1 is \s-\v$ (the system default value), and if it is, it sets PS1 to the value [\u@\h \W]\\$ .
If you want to see a custom prompt, however, you should not be editing /etc/bashrc . You should instead add it to .bashrc in your Home directory.
What do \u, \h, \W, \s, and \v mean? More Linux resources
- What is Linux?
- What are Linux containers?
- Download Now: Linux commands cheat sheet
- Advanced Linux commands cheat sheet
- Our latest Linux articles
In the PROMPTING section of man bash , you can find a description of all the special characters in PS1 and PS2 . The following are the default options:
What other special strings can I use in the prompts?
- \u : Username
- \h : Short hostname
- \W : Basename of the current working directory ( ~ for home, the end of the current directory elsewhere)
- \s : Shell name ( bash or sh , depending on how the shell is called)
- \v : The shell's version
There are a number of special strings that can be useful.
- \d : Expands to the date in the format "Tue Jun 27"
- \D{fmt} : Allows custom date formats!see man strftime for the available options
- \D{%c} : Gives the date and time in the current locale
- \n : Include a new line (see multi-line prompts below)
- \w : The full path of the current working directory
- \H : The full hostname for the current machine
- \! : History number!you can run any previous command with its history number by using the shell history event designator ! followed by the number for the specific command you are interested in. (Using Linux history is yet another tutorial...)
There are many other special characters!you can see the full list in the PROMPTING section of the Bash man page .
Multi-line promptsIf you use longer prompts (say if you include \H or \w or a full date-time ), you may want to break things over two lines. Here is an example of a multi-line prompt, with the date, time, and current working directory on one line, and username @hostname on the second line:
Are there any other interesting things I can do?PS1 = "\D{%c} \w \n [\u@\H]$ "
One thing people occasionally do is create colorful prompts. While I find them annoying and distracting, you may like them. For example, to change the date-time above to display in red text, the directory in cyan, and your username on a yellow background, you could try this:
PS1 = "\[\e[31m\]\D{%c}\[\e[0m\]
\[\e[36m\]\w\[\e[0m\] \n [\[\e[1;43m\]\u\[\e[0m\]@\H]$ "To dissect this:
- \[..\] declares some non-printed characters
- \e[.. is an escape character. What follows is a special escape sequence to change the color (or other characteristic) in the terminal
- 31m is red text ( 41m would be a red background)
- 36m is cyan text
- 1;43m declares a yellow background ( 1;33m would be yellow text)
- \[\e[0m\] at the end resets the colors to the terminal defaults
You can find more colors and tips in the Bash prompt HOWTO . You can even make text inverted or blinking! Why on earth anyone would want to do this, I don't know. But you can!
What are your favorite Bash prompt customizations? And which ones have you seen that drive you crazy? Let me know in the comments. Ben Cotton on 07 Jul 2017 Permalink I really like the Bash-Beautify setup by Chris Albrecht:
https://github.com/KeyboardCowboy/Bash-Beautify/blob/master/.bash_beautifyWhen you're in a version-controlled directory, it includes the VCS information (e.g. the git branch and status), which is really handy if you do development. Victorhck on 07 Jul 2017 Permalink An easy drag and drop interface to build your own .bashrc/PS1 configuration
've phun!
How Docker Is Growing Its Container Business (Apr 21, 2017, 07:00)
VIDEO: Ben Golub, CEO of Docker Inc., discusses the business of containers and where Docker is headed.
Understanding Shell Initialization Files and User Profiles in Linux (Apr 22, 2017, 10:00)
tecmint: Learn about shell initialization files in relation to user profiles for local user management in Linux.Cockpit An Easy Way to Administer Multiple Remote Linux Servers via a Web Browser (Apr 23, 2017, 18:00)
Cockpit is a free and open source web-based system management tool where users can easily monitor and manage multiple remote Linux servers.The Story of Getting SSH Port 22 (Apr 24, 2017, 13:00)
It's no coincidence that the SSH protocol got assigned to port 22.How To Suspend A Process And Resume It Later In Linux (Apr 24, 2017, 11:00)
This brief tutorial describes how to suspend or pause a running process and resume it later in Unix-like operating systems.
ShellCheck -A Tool That Shows Warnings and Suggestions for Shell Scripts (Apr 25, 2017, 06:00)
tecmint: ShellCheck is a static analysis tool that shows warnings and suggestions concerning bad code in bash/sh shell scripts.Quick guide for Linux check disk space (Apr 26, 2017, 14:00)
Do you know how much space is left on your Linux system?
Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.
# How many characters of the $PWD should be kept local pwdmaxlen=30 # Indicator that there has been directory truncation: #trunc_symbol="<" local trunc_symbol="..." if [ ${#PWD} -gt $pwdmaxlen ] then local pwdoffset=$(( ${#PWD} - $pwdmaxlen )) newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}" else newPWD=${PWD} fiThe above code can be executed as part of PROMPT_COMMAND, and the environment variable generated (newPWD) can then be included in the prompt. Thanks to Alexander Mikhailian <mikhailian at altern dot org> who rewrote the code to utilize new Bash functionality, thus speeding it up considerably.
Risto Juola (risto AT risto.net) wrote to say that he preferred to have the "~" in the $newPWD, so he wrote another version:
pwd_length=20 DIR=`pwd` echo $DIR | grep "^$HOME" >> /dev/null if [ $? -eq 0 ] then CURRDIR=`echo $DIR | awk -F$HOME '{print $2}'` newPWD="~$CURRDIR" if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ] then newPWD="~/..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")" fi elif [ "$DIR" = "$HOME" ] then newPWD="~" elif [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ] then newPWD="..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")" else newPWD="$(echo -n $PWD)" fiRelative speed: the first version takes about 0.45 seconds on an unloaded 486SX25. Risto's version takes about 0.80 to 0.95 seconds. The variation in this case is due to whether or not truncation is required.
Setting the Primary Prompt StringUsing the environment variable PS1, users can create a dynamic prompt string. Here's a common example using Korn shell environmental variables:
export PS1='$LOGNAME@$SYSNAME:$PWD'":> "Since environmental variable PWD is dynamically set by the cd command, each time the directory changes, our PS1 displays the system name, the user name, and the current working directory.According to Bolsky and Korn, the "ksh performs parameter expansion, arithmetic expansion, and command substitution on the value of PS1 each time before displaying the prompt". However, not all implementations of the Korn shell provide all of these features.
The version of the Korn shell we use most often performs parameter expansion but not command substitution. Under these conditions, suppose we want the prompt string to only display the last two directories of the current working directory's full pathname. For example, if PWD were:
/home/eds/jspurgeo/myentry/srcwe only want to see:myentry/srcHere's one way to solve the problem:export PS1='${PWD##/*/*}${PWD#${PWD%/*/*}} >'To simplify the explanation, we break the solution into three pieces:
- With ${PWD%/*/*} -- The % operator matches the end of the PWD variable for everything between two slashes. This leaves an intermediate string, which is actually what should be deleted.
- Match the beginning of the PWD directory with the intermediate string using the # operator: ${PWD#${PWD%/*/*}}, which deletes the start of the string leaving only the last two directories.
- The second step doesn't solve the special case where PWD is less than two directories, that is, /tmp, /. So, we perform a final match using the ## operator:
${PWD##/*/*}${PWD#${PWD%/*/*}}If the PWD string contains two or less slashes, don't delete anything.
(Score:1)
by westrick (245730) on Wednesday February 07, @10:49AM (#449478)PS1=`uname -n`':${PWD#$OLDPWD/}$
' Just enough info about where I am, without wasting the entire screen with $PWD.
- X-seq: zsh-users 840
- From: Steve <steve@xxxxxxxxxx>
- To: Tom Kirkpatrick <tomk@xxxxxxx>
- Subject: Re: Does zsh have equivalent to $PROMPT_COMMAND
- Date: Wed, 23 Apr 1997 18:07:58 -0700
- Cc: zsh-users@xxxxxxxxxxxxxxx
> The only feature of bash i miss in zsh is the variable > $PROMPT_COMMAND if set in .bashrc everytime you login for the entire > session the command defined as the variable, is executed before each > prompt.
Zsh does not have a $PROMPT_COMMAND variable, AFAIK. Instead, you can define the precmd _function_ which is executed before each prompt. Other special functions are listed in the zshmisc(1) man page.
Using a function for this is more logical than using a variable, IMHO.
- To: Tim Jones <[email protected]>
- Subject: Re: sudo and shell prompt.
- From: "Todd C. Miller" <[email protected]>
- Date: Sat, 15 Sep 2001 13:24:56 -0600
- Cc: [email protected]
- References: <[email protected]>
You should be able to set the SUDO_PS1 environment variable and have a custom prompt for your "sudo bash" shells.
Of course, a big reason to use sudo is to _avoid_ using a root shell, but to each his own.
- todd
4.1. PROMPT_COMMANDBash provides an environment variable called PROMPT_COMMAND. The contents of this variable are executed as a regular Bash command just before Bash displays a prompt.
[21:55:01][giles@nikola:~] PS1="[\u@\h:\w]\$ " [giles@nikola:~] PROMPT_COMMAND="date +%H%M" 2155 [giles@nikola:~] d bin mail 2156 [giles@nikola:~]What happened above was that I changed PS1 to no longer include the \t escape sequence (added in a previous section), so the time was no longer a part of the prompt. Then I used date +%H%M to display the time in a format I like better. But it appears on a different line than the prompt. Tidying this up using echo -n ... as shown below works with Bash 2.0+, but appears not to work with Bash 1.14.7: apparently the prompt is drawn in a different way, and the following method results in overlapping text.
2156 [giles@nikola:~] PROMPT_COMMAND="echo -n [$(date +%H%M)]" [2156][giles@nikola:~]$ [2156][giles@nikola:~]$ d bin mail [2157][giles@nikola:~]$ unset PROMPT_COMMAND [giles@nikola:~]echo -n ... controls the output of the date command and suppresses the trailing newline, allowing the prompt to appear all on one line. At the end, I used the unset command to remove the PROMPT_COMMAND environment variable.
11.10. Controlling the Size and Appearance of $PWD
Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.
# How many characters of the $PWD should be kept local pwdmaxlen=30 # Indicator that there has been directory truncation: #trunc_symbol="<" local trunc_symbol="..." if [ ${#PWD} -gt $pwdmaxlen ] then local pwdoffset=$(( ${#PWD} - $pwdmaxlen )) newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}" else newPWD=${PWD} fi
Simple Red-hat style prompt:
function redhat {
PS1="[\u@\h \W]\\$ "
PS2="> "
}Colored prompt
#!/bin/bash
function proml {
local BLUE="\[\033[0;34m\]"
local RED="\[\033[0;31m\]"
local LIGHT_RED="\[\033[1;31m\]"
local WHITE="\[\033[1;37m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esacPS1="${TITLEBAR}\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$LIGHT_RED\u@\h:\w$BLUE]\
$WHITE\$$LIGHT_GRAY "
PS2='> '
PS4='+ '
}
#!/bin/bash
# termwide prompt with tty number
# by Giles - created 2 November 98
#
# $Revision: 1.2 $ $Author: giles $
# $Source: /home/giles/.bashprompt/bashthemes/RCS/twtty,v $
# $Log: twtty,v $
# Revision 1.2 1999/03/25 01:37:51 giles
#
# Revision 1.1 1999/03/25 01:35:26 giles
# Initial revision
#
# This is a variant on "termwide" that incorporates the tty number.
#
# 24 March 99 - use of sed with \{$cut\} where $cut is an integer
# means that this probably now requires a GNU version of sed.function prompt_command {
TERMWIDTH=${COLUMNS}
# Calculate the width of the prompt:
hostnam=$(echo -n $HOSTNAME | sed -e "s/[\.].*//")
# "whoami" and "pwd" include a trailing newline
usernam=$(whoami)
cur_tty=$(tty | sed -e "s/.*tty\(.*\)/\1/")
newPWD="${PWD}"
# Add all the accessories below ...
let promptsize=$(echo -n "--(${usernam}@${hostnam}:${cur_tty})---(${PWD})--" \
| wc -c | tr -d " ")
let fillsize=${TERMWIDTH}-${promptsize}
fill=""
while [ "$fillsize" -gt "0" ]
do
fill="${fill}-"
let fillsize=${fillsize}-1
doneif [ "$fillsize" -lt "0" ]
then
let cut=3-${fillsize}
newPWD="...$(echo -n $PWD | sed -e "s/\(^.\{$cut\}\)\(.*\)/\2/")"
fi
}PROMPT_COMMAND=prompt_command
function twtty {
local GRAY="\[\033[1;30m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
local WHITE="\[\033[1;37m\]"
local NO_COLOUR="\[\033[0m\]"local LIGHT_BLUE="\[\033[1;34m\]"
local YELLOW="\[\033[1;33m\]"case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esacPS1="$TITLEBAR\
$YELLOW-$LIGHT_BLUE-(\
$YELLOW\$usernam$LIGHT_BLUE@$YELLOW\$hostnam$LIGHT_BLUE:$WHITE\$cur_tty\
${LIGHT_BLUE})-${YELLOW}-\${fill}${LIGHT_BLUE}-(\
$YELLOW\${newPWD}\
$LIGHT_BLUE)-$YELLOW-\
\n\
$YELLOW-$LIGHT_BLUE-(\
$YELLOW\$(date +%H%M)$LIGHT_BLUE:$YELLOW\$(date \"+%a,%d %b %y\")\
$LIGHT_BLUE:$WHITE\$$LIGHT_BLUE)-\
$YELLOW-\
$NO_COLOUR "PS2="$LIGHT_BLUE-$YELLOW-$YELLOW-$NO_COLOUR "
}
Root prompt
#!/bin/bash
# $Author: giles $, $Date: 1999/07/29 17:59:59 $
# $Source: /home/giles/.bashprompt/bashthemes/RCS/rprom,v $
# $Revision: 1.3 $
#
# $Log: rprom,v $
# Revision 1.3 1999/07/29 17:59:59 giles
# Terminated colours correctly at prompt end.
#
# Revision 1.2 1999/06/06 18:13:30 giles
# Made the length of the kept part of the PWD flexible - a variable
# named near the beginning of the script.
#
# Revision 1.1 1999/06/06 18:02:35 giles
# Initial revision
#function prompt_command {
# How many characters of the $PWD should be kept
local pwd_length=30
# Create TotalMeg variable: sum of visible file sizes in current directory
local TotalBytes=0
for Bytes in $(ls -l | grep "^-" | cut -c30-41)
do
let TotalBytes=$TotalBytes+$Bytes
done
TotalMeg=$(echo -e "scale=3 \nx=$TotalBytes/1048576\n if (x<1) {print \"0\"} \n
print x \nquit" | bc)# Count visible files:
let files=$(ls -l | grep "^-" | wc -l | tr -d " ")
let hiddenfiles=$(ls -l -d .* | grep "^-" | wc -l | tr -d " ")
let executables=$(ls -l | grep ^-..x | wc -l | tr -d " ")
let directories=$(ls -l | grep "^d" | wc -l | tr -d " ")
let hiddendirectories=$(ls -l -d .* | grep "^d" | wc -l | tr -d " ")-2if [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
newPWD="...$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
newPWD="$(echo -n $PWD)"
fi
}PROMPT_COMMAND=prompt_command
function rprom {
local BLUE="\[\033[0;34m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
local LIGHT_GREEN="\[\033[1;32m\]"
local LIGHT_BLUE="\[\033[1;34m\]"
local LIGHT_CYAN="\[\033[1;36m\]"
local YELLOW="\[\033[1;33m\]"
local WHITE="\[\033[1;37m\]"
local RED="\[\033[0;31m\]"
local NO_COLOUR="\[\033[0m\]"case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esacPS1="$TITLEBAR\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$RED\u@\h$BLUE]\
$BLUE[\
$LIGHT_GRAY\${files}.\${hiddenfiles}-\
$LIGHT_GREEN\${executables}x \
$LIGHT_GRAY(\${TotalMeg}Mb) \
$LIGHT_BLUE\${directories}.\
\${hiddendirectories}d\
$BLUE]\
\n\
$BLUE[$RED\$newPWD$BLUE]\
$WHITE\$\
\
$NO_COLOUR "
PS2='> '
PS4='+ '
}
---------------------- Begin Copyrighted Material ------------------- $Revision: 1.11 $ $Date: 2003/01/19 06:17:23 $This article is Copyright 1998-2003 by Douglas Barton. All non-commercial uses of this article are granted explicitly; providing that my name, this copyright notice, and all material between and including the lines that say "Begin Copyrighted Material" and "End of Copyrighted Material" are reproduced intact. All commercial uses of this article are explicitly reserved, and must be arranged with the author.
I hope that does not sound extreme, but writing documentation is one of the things I do for a living, and after putting as many hours into something as I have this article, I feel that protecting my interests is well within reason. :) Please feel free to send any comments, suggestions, corrections or questions to [email protected].
I made reference to the "termcap" file that comes with the FreeBSD distribution, the xterm source code, and the "ctlseqs.ms," both from XFree86 3.3.2.3. Of course I also used the Bash man pages.
The information in this article is specific to Bash version 2.x. Although the general information about xterm and ANSI escape sequences is probably applicable to other shells, I have not tested it, and have no intention of doing so. Those using Bash 1.14.x can accomplish most of the things mentioned here by using the octal equivalents of the various escape sequences (e.g., substituting \033 for \e, \007 for \a, etc.) and deleting the \[ and \] characters that indicate the boundaries of the non-printable portions of the prompt to Bash 2. This was tested briefly, but I give no guarantees that what you want to do with Bash 1.14 will work.
If you need help with the basics of creating a prompt string, please see the PROMPTING section of the Bash man page.
By including escape sequences in your prompt you can affect various aspects of the terminal you are using; be that an xterm, console device, or other terminal emulation. For example, xterm has the following built in escape sequences (from misc.c in the xterm source):
0: /* new icon name and title*/ 1: /* new icon name only */ 2: /* new title only */The icon name escape sequences work for X window managers like AfterStep and Window Maker. The title bar sequences work in most window managers. Both also work for some Windows based terminal emulators. An example is PuTTY, which can be found at http://www.chiark.greenend.org.uk/~sgtatham/putty/
Here is a simple example of a prompt using those attributes.
PS1='\[\e]1;My Desk\a\e]2;${PWD}\a\]\ [\u@ME \w]\n \#\$ 'To make things easier to read, I used a \ at the end of the first line (which is interpreted by the shell as literally escaping the Return at the end of that line) to continue the string onto the next line. You can use all the examples in this article as they are here, or you can join the lines. Make sure to delete the \ if you join them. Here is how to interpret the elements of that line.PS1= set the shell variable PS1 equal to the string between the two ' marks. Since this variable is only used by Bash, there is no need to export it. \[ start a sequence of non-printing characters \e an ASCII escape character (033 octal) ]1; xterm escape sequence for the name of the icon My Desk literal text string \a an ASCII bell character (007 octal)This ends the first xterm sequence.\e]2;${PWD}\aPut the present working directory in the xterm titlebar. I like to use ${PWD} here because \w puts ~ in the title when you use just 'cd' to return to your home.\] ends the non-printing character sequence [\u@ME \w]\n [ literal [ character \u the username of the current user @ME literal characters \w the current working directory ] literal ] character \n newline \#\$ \# the command number of this command \$ if the effective UID is 0, a #, otherwise a $Here are some examples of what the prompt looks like using the above string.While I am in my home directory:
[myusername@ME ~] 22$ Another directory: [myusername@ME /usr/ports/shells/bash2] 23$Now assume you would like to add color to your prompt. The following will make your prompt a lovely shade of blue, with the caveat that not all ANSI sequences display exactly the same on all terminals.PS1='\[\e]1;My Desk\a\e]2;${PWD}\a\ \e[0;34m\]\ [\u@ME \w]\n \#\$ \ \[\e[m\]'The astute reader will notice that there are two changes to the previous string. Before the first \] which indicates the end of the non-printing sequence, the ANSI escape code for the color blue was added.\e[ ANSI escape sequence indicator 0; use the default attribute (i.e., no bold, underline, etc.) 34 use blue for the foreground color m end of ANSI escape indicatorAt the end of the prompt we have included another set of non-printable characters with the ANSI escape sequence for "cancel all attributes." This will prevent the text you type in at the prompt from being colored, or otherwise affected.Two very popular uses of color are to indicate that the user has become root, and to use different colors for prompts on different hosts. Because I log into machines on a lot of different hosts, I have developed the following prompt system which allows me to simply change the two variables below for each host.
PROMPT_HOSTNAME='ME' PROMPT_COLOR='0;34m' # If I am root, set the prompt to bright red if [ ${UID} -eq 0 ]; then PROMPT_COLOR='1;31m' fi PS1='\[\e]1;${PROMPT_HOSTNAME}\a\e]2;${PROMPT_HOSTNAME}:${PWD}\a\ \e[${PROMPT_COLOR}\]\ [\u@${PROMPT_HOSTNAME} \w]\n \#\$ \ \[\e[m\]'There are other ANSI attributes that can be added, such as bold, inverse (or reverse) video, blink and underline. Not all attributes are supported on all terminals however. For example, the blink attribute is not available in xterm. Underline is generally not available in cons25. A little experimentation with your terminal type will show you what you need to do to achieve the effect you want.A chart with the most common escape sequences of interest; and which ones are supported on xterm, cons25 and vt100 terminals is appended to the end of this article. If your system uses terminfo instead of termcap, your escape codes may be different.
Let us say that you would like the hostname part of the prompt to be in reverse video so that it stands out more than the rest.
PS1='\[\e[0;34m\]\ [\u@\e[7mME\e[27m \w]\n \#\$ \ \[\e[m\]'The \e[7m sequence is the code for reverse video. On an xterm you can use the sequence \e[27m to cancel the reverse attribute. On other terminals you would either have to use \e[m to cancel all attributes (which works fine if you are not using color) or use the same color sequence you used previously to restore only the color attribute.If you have the same .bash_profile/.bashrc on a machine that you log into from different terminal types, you may find the following to be of use. This allows you to customize your prompt according to what attributes are supported based on the various types of terminals you use. This is based on my experience, you will probably need to modify it to serve your needs.
PROMPT_HOSTNAME='ME' PROMPT_COLOR='0;34m' # If I am root, set the prompt to bright red if [ ${UID} -eq 0 ]; then PROMPT_COLOR='1;31m' fi case ${TERM} in xterm*) PS1='\[\e]1;${PROMPT_HOSTNAME}\a\e]2;${PROMPT_HOSTNAME}:${PWD}\a\ \e[${PROMPT_COLOR}\][\u@${PROMPT_HOSTNAME} \w]\n \#\$ \[\e[m\]' ;; vt100) PS1='[\u@${PROMPT_HOSTNAME} \w]\n \#\$ ' ;; *) PS1='\[\e[${PROMPT_COLOR}\][\u@${PROMPT_HOSTNAME} \w]\n \#\$ \[\e[m\]' ;; esacBelow is a chart of various interesting attributes for prompting purposes. The first column is a description of the attribute. The second column is the termcap code for that attribute. For more information check 'man 5 termcap'. If the escape code listed does not work for your terminal, check the termcap file for your machine. Those using the terminfo system should check that file and the documentation for it to find the information they need.The last three columns contain the codes for the various terminals, if they are supported. Below this chart is a very long and rather obnoxious prompt string that gives examples of these attributes, and should allow you to test your terminal to see what it can support. It also has the various color codes so you can use it as a reference as well. The bold attribute when combined with a color has the effect of "brightening" the color displayed. On some terminals this makes it an entirely different color.
When creating an escape sequence, you can combine the various elements. For example, if you want a string that is bold, underlined, with a red foreground and a green background you would use:
\e[1;4;31;42mTo read this chart, keep in mind that an ANSI escape sequence starts with \e[ and ends with a literal m. Thus from the chart, the code to turn on the bold attribute is \e[1m. The \e[m sequence turns off all ANSI attributes, and is the only way to cancel things like bold and underline on most terminals. Obviously, "NO" means that terminal does not support that attribute. The ^G for bell is the traditional "hold down the Control key and press G" combination. It can of course be represented in a Bash 2 prompt string with \a. On most terminals, "inverse" and "standout" are identical. Most terminals display unsupported attributes as bold.Attribute termcap xterm cons25 vt100 --------------------------------------------- bold on md 1 1 1 bold off 22 [m inverse on mr 7 7 7 inverse off 27 [m standout on so 7 7 7 standout off se 27 [m [m underline on us 4 NO 4 underline off ue 24 [m blink on mb NO 5 5 blink off 25 [m [m blank/invis mk 8 bell bl ^G ^G ^G all attr off me [m [m [mHere is a sample prompt with the list of color codes included. Where more than one color is indicated it means that color is known to display differently on different terminal types. Other colors may be similarly affected.PS1='[\u@TEST \w]\n \#\$ \n\ \[\ \e[1mBold Text\e[m\n\ \e[4mUnderline Text\e[m\n\ \e[5mBlink Text\e[m\n\ \e[7mInverse Text\e[m\]\n\ Should be normal text Foreground colors: \[\ \e[0;30m30: Black\n\ \e[0;31m31: Red\n\ \e[0;32m32: Green\n\ \e[0;33m33: Yellow\Orange\n\ \e[0;34m34: Blue\n\ \e[0;35m35: Magenta\n\ \e[0;36m36: Cyan\n\ \e[0;37m37: Light Gray\Black\n\ \e[0;39m39: Default\n\ Bright foreground colors: \e[1;30m30: Dark Gray\n\ \e[1;31m31: Red\n\ \e[1;32m32: Green\n\ \e[1;33m33: Yellow\n\ \e[1;34m34: Blue\n\ \e[1;35m35: Magenta\n\ \e[1;36m36: Cyan\n\ \e[1;37m37: White\n\ \e[0;39m39: Default\n\ \e[m\]Background colors: \[\e[1;37m\e[40m40: Black\e[0;49m\n\ \e[41m41: Red\e[0;49m\n\ \e[42m42: Green\e[0;49m\n\ \e[43m43: Yellow\Orange\e[0;49m\n\ \e[44m44: Blue\e[0;49m\n\ \e[45m45: Magenta\e[0;49m\n\ \e[46m46: Cyan\e[0;49m\n\ \e[47m47: Light Gray\Black\e[0;49m\n\ \e[49m49: Default\e[m\]\n'While I know that nothing in this article is going to cure cancer, I hope that it does bring some small joy to your life, and that you have as much fun using this information as I did bringing it all together.
-------------------- End of Copyrighted Material -----------------------
An excellent web page with resources for other shells can be found at: http://sunsite.unc.edu/LDP/HOWTO/mini/Xterm-Title.html
The Linux Bash prompt HOWTO maintained by Giles Orr can be found at: http://www.dreaming.org/~giles/bashprompt/ There are a lot of interesting ideas in that extensive document, but he makes use of a lot of external programs in his prompts (even when he doesn't have to), which is something I think is a little excessive. But each to his own. :)
http://en.tldp.org/HOWTO/Bash-Prompt-HOWTO/index.html
Google matched content |
Please visit Heiner Steven SHELLdorado the best shell scripting site on the Internet |
Google Directory - Computers Software Operating Systems Unix Shell bash
Sys Admin v15, i12 Korn Shell Nuances (only the last part of the article is relevant to the topic).
Enhancing Shell Prompts by Daniel Robbins ([email protected]) President-CEO, Gentoo Technologies, Inc. September 2000
Why stick with the standard boring shell prompt when you can easily make it colorful and more informative? In this tip, Daniel Robbins will show you how to get your shell prompt just the way you like it, as well as how to dynamically update your X terminal's title bar.
Highlighting Linux Command Prompts with the PROMPT_COMMAND Variable by Kirk Becker Sys Admin Magazine vol. 12, No. 1 January, 2003
ONLamp.com Understanding Shell Prompts
Bash-prompts Copyright 1998-2003 by Douglas Barton.
$Revision: 1.11 $ $Date: 2003/01/19 06:17:23 $ All non-commercial uses of this article are granted explicitly; providing that my name, this copyright notice, and all material between and including the lines that say "Begin Copyrighted Material" and "End of Copyrighted Material" are reproduced intact. All commercial uses of this article are explicitly reserved, and must be arranged with the author.
Prompt Depending on Connection Type -- interesting idea from the point view of security
170_myprompt --readymade, pretty complex color prompt.
LinuxLookup.com Articles Shell Prompt Customization -- some simpler prompt variants (bash)
Bash Prompt HOWTO Example Prompts -- prompt perversions. Well, if you like stuff like this, you should definitely have a look at BASHISH, the shell prompt theme (no RPMs, though).
[Nov 24, 2004] Bash Prompt HOWTO. Bash Prompt HOWTO -- this is an overkill ;-), but still there is a useful information, for example: 11.10. Controlling the Size and Appearance of $PWD
Unix allows long file names, which can lead to the value of $PWD being very long. Some people (notably the default RedHat prompt) choose to use the basename of the current working directory (ie. "giles" if $PWD="/home/giles"). I like more info than that, but it's often desirable to limit the length of the directory name, and it makes the most sense to truncate on the left.
# How many characters of the $PWD should be kept local pwdmaxlen=30 # Indicator that there has been directory truncation: #trunc_symbol="<" local trunc_symbol="..." if [ ${#PWD} -gt $pwdmaxlen ] then local pwdoffset=$(( ${#PWD} - $pwdmaxlen )) newPWD="${trunc_symbol}${PWD:$pwdoffset:$pwdmaxlen}" else newPWD=${PWD} fiThe above code can be executed as part of PROMPT_COMMAND, and the environment variable generated (newPWD) can then be included in the prompt. Thanks to Alexander Mikhailian <mikhailian at altern dot org> who rewrote the code to utilize new Bash functionality, thus speeding it up considerably.
Risto Juola (risto AT risto.net) wrote to say that he preferred to have the "~" in the $newPWD, so he wrote another version:
pwd_length=20 DIR=`pwd` echo $DIR | grep "^$HOME" >> /dev/null if [ $? -eq 0 ] then CURRDIR=`echo $DIR | awk -F$HOME '{print $2}'` newPWD="~$CURRDIR" if [ $(echo -n $newPWD | wc -c | tr -d " ") -gt $pwd_length ] then newPWD="~/..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")" fi elif [ "$DIR" = "$HOME" ] then newPWD="~" elif [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ] then newPWD="..$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")" else newPWD="$(echo -n $PWD)" fiRelative speed: the first version takes about 0.45 seconds on an unloaded 486SX25. Risto's version takes about 0.80 to 0.95 seconds. The variation in this case is due to whether or not truncation is required.
The FreeBSD Diary -- Changing your bash prompt. See also Bash-prompts
Then I added the following to the bottom of .bash_profile:
# set prompt: ``username@hostname:/directory $ '' PS1="[\u@\h:\w] " case `id -u` in 0) PS1="${PS1}# ";; *) PS1="${PS1}$ ";; esacThis will give you a prompt something like this:
[fleur@flossy:/usr/home/fleur]#
Linux Orbit - Server or desktop, GNU-Linux just works -- Useful description of PS1 and PS2 in bash (non-applicable to korn shell)
The
PS1
variable is your primary prompt. Depending upon how your system is configured, thePS1
variable will vary.PS1
is normally defined in/etc/profile
, but can be overridden by defining it again in~/.bash_profile
[TRANSLATION: Because/etc/profile
is only writable by root, you can only override the environmental variables there by redefining them in your~/.bash_profile
].bash
recognizes special characters prefixed with a backslash for thePS1
variable. These characters are:
t -- the current time in HH:MM:SS format
d -- the date in "Weekday Month Date" format (eg, "Tue May 26")
newline
s -- the name of the shell
w -- the current working directory
W -- the basename of the current working directory
u -- the username of the current user
h -- the hostname
# the command number of this command
! -- the history number of this command
$ -- if the effective UID is 0, a #, otherwise a $These are the characters that allow you to change your prompt. If your
PS1
variable is set asPS1="[u@h W]$"
, then your prompt will look like this:
[xconsole@localhost /etc]$
If you were to change it to the following:
PS1="[\t\s]$ "
, you would get:
[12:18:24 bash]$
In addition to these special backslash characters, you can use commands. For instance, to have your prompt run as a fortune, you can do this:
PS1="`fortune` $ "
Notice that you have to use "
`
" instead of "'
". This changesPS1
to the following:
He is no lawyer who cannot take two sides. $
As you can see,
bash
is very lenient about the way you configure it, so knock yourself out. ThePS2
variable is your secondary prompt and is used when you have typed an incomplete command, or when you have typed a backslash at the end of a command [TRANSLATION: A backslash at the end of a command inbash
tells it that you are not done with the command. This is when it will present you with thePS2
variable.bash
is also smart enough to know when the command you are typing is incomplete, and in such a case, it will present you with thePS2
variable]. When you are presented with thePS2
variable,bash
expects you to finish the command before it will attempt to run it. To see your currentPS2
variable, run the following command:
xconsole$ if [ -f /etc/profile ]; then
When you press ENTER, you will see that you have a new prompt:
xconsole$ if [ -f /etc/profile ]; then >
This prompt is the
PS2
variable. You can also view it withecho $PS2
. In the above example with theif
statement, we did not add a backslash character right at the end of the command, butbash
knew the command was incomplete. As withPS1
, it is defined in/etc/profile
, and can be overridden and redefined in~/.bash_profile
. It recognizes the special backslashed characters, as well as other programs likefortune
[TRANSLATION: Whatever applies toPS1
, applies toPS2
as well].
Setting the PS1 Environment Variable In Redhat Linux Distributions
There have been instances where administrators have had difficulty setting the PS1 environment variable on their system when using Redhat Linux distributions. The PS1 environment variable controls the prompt on the command line, and can be used by users to tell what system they are on, the directory they are currently in, the current date and more depending on how this variable is configured. This tip will explain the strange method used by Redhat distributions to control the PS1 variable, and the options administrators have to work around it.
Understanding the Problem
When Bash begins to run when the user logs in, the following sequence of events will normally occur unless Bash is invoked with the -noprofile option. These events are specific for a common Redhat distribution upon initial install. Please see the How Linux Works CTDP Guide for complete information on files that are run when bash starts, or read the bash(1) man page.
- Bash runs /etc/profile if it exists
- Bash runs $HOME/.bash_profile
- The $HOME/.bash_profile script runs the $HOME/.bashrc script
- The $HOME/.bashrc script runs /etc/bashrc
Note: The $HOME name used above indicates the user home directory. If you examine the sequence of events above, it is obvious that the last step is rather unusual. Normally scripts are run for system wide control, then scripts that are individually set up for specific users are run last. In the above sequence of events a script set for system control is run after running two scripts that are in the user's home directory. This has the effect of stepping on any values any individual user may set the PS1 environment variable to. When a user makes a modification to this variable in the .bash_profile script in their home directory, the change will be ineffective. This is because the /etc/bashrc file contains the following:
# /etc/bashrc # System wide functions and aliases # Environment stuff goes in /etc/profile # For some unknown reason bash refuses to inherit # PS1 in some circumstances that I can't figure out. # Putting PS1 here ensures that it gets loaded every time. PS1="[\u@\h \W]\\$ "This will set the PS1 variable to the value shown here. The PS1 value is normally initially set in the /etc/profile script for system wide default use, then the individual users may modify or change this value in the $HOME/.bash_profile script for their own use. If you note the comment above, the writer of the /etc/bashrc file states that "bash refuses to inherit PS1 in some circumstances".
Solving the Problem
Normally, the correct thing to do would be to run the /etc/bashrc script from the /etc/profile script. The /etc/bashrc script should not change the PS1 variable, but is normally used to set up aliases, Therefore in addition to doing the below changes the administrator may want to comment out the line in /etc/bashrc that sets the PS1 variable, and add the three lines from the $HOME/.bashrc file that run the /etc/bashrc script to the end of the /etc/profile script. The /etc/bashrc script can then be used by the administrator for setting global alias values.
I think setting the PS1 variable in the $HOME/.bash_profile or $HOME/.bashrc script should be sufficient to avoid the above problem so long as you be sure to set it. Since the $HOME/.bashrc file contains the following:
# .bashrc # User specific aliases and functions # Source global definitions if [ -f /etc/bashrc ]; then . /etc/bashrc fiThe easiest thing to do is comment out the three lines that make up the if statement (put the # character at the start of each line), which would run the /etc/bashrc script and add the following line or one like it to the file to set the PS1 value.
PS1="[\u@\h \w]\\$ "
This line can be added to the $HOME/.bash_profile script file instead but would involve changing two files. Adding it to the $HOME/.bash_profile script is the more appropriate thing to do from a system standpoint since the $HOME/.bashrc file is for aliases. The administrator would want to make these changes to all these files in their user's home directories, or have their users do it.
Making the change for all future users
The directory /etc/skel contains files that are used by the system to create files for new users in their home directories. To make this change effective for users that are added to the system in the future, the /etc/skel/.bashrc file should be changed and the /etc/skel/.bash_profile file should be changed if it was used to set the PS1 variable.
The meaning of the characters in the prompt string settings
The following list shows the meanings of the special characters used to define the PS1 and PS2 prompt strings.
- \t - time
- \d - date
- \n - newline
- \s - Shell name
- \W - The current working directory
- \w - The full path of the current working directory.
- \u - The user name
- \h - Hostname
- \# - The command number of this command.
- \! - The history number of the current command
If you want the full path of the current directory, use a small w in the string shown above. Read the bash(1) man page for more information. Also read The Bash Reference Manual in the directory /usr/doc/bash2-doc-2.03/bash.ps. It can be accessed from an X session by double clicking on it while using the file manager. Bash builtins are described in the file in the directory /usr/doc/bash2-doc-2.03/builtins.ps.
Comments or Problems
If anyone finds that they have some difficulties in making this change that may be related to this tip, please send an email to the administrator of this website describing the distribution of Linux being used, the version of bash and any other circumstances that pertain to the problem. Also include copies of $HOME/.bash_profile, and $HOME/.bashrc. We cannot guarantee a response, but will do what we can to look into the problem and update the tip as it is appropriate.
- Date of Original Tip:
- July 12, 2000
- Author:
- Mark Allen
My PS1 prompt has the following string,
PS1='($?)\u@\h:\w =>'
In this case, when my command fails the BASH variable $? value is displayed
in my prompt. What is happening is that a command return value stays there
until an new command is issued. A newline for the shell will still return the
previous $? value. $? value is never reset until a new command is issued.(0)subb3@myhost:~ =>
(0)subb3@myhost:~ => lssdfh <== This is no command
(258)subb3@myhost:~ =>
(258)subb3@myhost:~ =>
(258)subb3@myhost:~ =>
(258)subb3@myhost:~ => ls
<file listing>
(0)subb3@myhost:~ =>When I change the PS1 sring to,
PS1='($?)`whoami`@\h:\w =>'
The return value for $? is immediately displayed in the next prompt.
(0)subb3@myhost:~ =>
(0)subb3@myhost:~ => lssdfh
(258)subb3@myhost:~ =>
(0)subb3@myhost:~ =>
(0)subb3@myhost:~ => ls
<file listing>
(0)subb3@myhost:~ => ls o
ls: o: No such file or directory
(1)subb3@myhost:~ =>In BASH, why does the "\u" and "whoami" make a big difference for the $? value in
PS1 string? The BASH version is 2.04.--
Subba Rao
[email protected]
http://pws.prserv.net/truemax/=> Time is relative. Here is a new way to look at time. <=
http://www.smcinnovations.com
> $? value is never reset until a new command is issued.
Of course, since it's the exit status of the last command.> PS1='($?)`whoami`@\h:\w =>'
>
> The return value for $? is immediately displayed in the next prompt.
It's the exit status of the command substitution, the last command
executed.--
``The lyf so short, the craft so long to lerne.'' - Chaucer
( ``Discere est Dolere'' -- chet)Chet Ramey, CWRU [email protected] http://cnswww.cns.cwru.edu/~chet/
Bash escape sequences
When executing interactively, bash displays the primary prompt PS1 when it is ready
to read a command, and the secondary prompt PS2 when it needs more input
to complete a command. Bash allows these prompt strings to be customized by
inserting a number of backslash-escaped special characters that are decoded as follows:
\a
an ASCII bell character (07)
\d
the date in "Weekday Month Date" format
(e.g., "Tue May 26")
\e
an ASCII escape character (033)
\h
the hostname up to the first `.'
\H
the hostname
\j
the number of jobs currently managed by the shell
\l
the basename of the shell's terminal device name
\n
newline
\r
carriage return
\s
the name of the shell, the basename of $0 (the portion following the final slash)
\t
the current time in 24-hour HH:MM:SS format
\T
the current time in 12-hour HH:MM:SS format
\@
the current time in 12-hour am/pm format
\u
the username of the current user
\v
the version of bash (e.g., 2.00)
\V
the release of bash, version + patchlevel (e.g., 2.00.0)
\w
the current working directory
\W the
basename of the current working directory
\!
the history number of this command
\#
the command number of this command
\$
if the effective UID is 0, a #, otherwise a $
\nnn the
character corresponding to the octal
number nnn
\\
a backslash
\[
begin a sequence of non-printing characters,
which could be used to embed a terminal con
trol sequence into the prompt
\]
end a sequence of non-printing characters
developerWorks Linux Tip Prompt magic -- nice table of special characters in PS1-PS4.
Sequence Description \a The ASCII bell character (you can also type \007) \d Date in "Wed Sep 06" format \e ASCII escape character (you can also type \033) \h First part of hostname (such as "mybox") \H Full hostname (such as "mybox.mydomain.com") \j The number of processes you've suspended in this shell by hitting ^Z \l The name of the shell's terminal device (such as "ttyp4") \n Newline \r Carriage return \s The name of the shell executable (such as "bash") \t Time in 24-hour format (such as "23:01:01") \T Time in 12-hour format (such as "11:01:01") \@ Time in 12-hour format with am/pm \u Your username \v Version of bash (such as 2.04) \V Bash version, including patchlevel \w Current working directory (such as "/home/drobbins") \W The "basename" of the current working directory (such as "drobbins") \! Current command's position in the history buffer \# Command number (this will count up at each prompt, as long as you type something) \$ If you are not root, inserts a "$"; if you are root, you get a "#" \xxx Inserts an ASCII character based on three-digit number xxx (replace unused digits with zeros, such as "\007") \\ A backslash \[ This sequence should appear before a sequence of characters that don't move the cursor (like color escape sequences). This allows bash to calculate word wrapping correctly. \] This sequence should appear after a sequence of non-printing characters. So, there you have all of bash's special backslashed escape sequences. Play around with them for a bit to get a feel for how they work. After you've done a little testing, it's time to add some color.
Bash Prompt HOWTO -- this is an overkill ;-)
Simple Red-hat style prompt:
function redhat {
PS1="[\u@\h \W]\\$ "
PS2="> "
}
Colored prompt
#!/bin/bash
function proml {
local BLUE="\[\033[0;34m\]"
local RED="\[\033[0;31m\]"
local LIGHT_RED="\[\033[1;31m\]"
local WHITE="\[\033[1;37m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esacPS1="${TITLEBAR}\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$LIGHT_RED\u@\h:\w$BLUE]\
$WHITE\$$LIGHT_GRAY "
PS2='> '
PS4='+ '
}
Root prompt
#!/bin/bash
# $Author: giles $, $Date: 1999/07/29 17:59:59 $
# $Source: /home/giles/.bashprompt/bashthemes/RCS/rprom,v $
# $Revision: 1.3 $
#
# $Log: rprom,v $
# Revision 1.3 1999/07/29 17:59:59 giles
# Terminated colours correctly at prompt end.
#
# Revision 1.2 1999/06/06 18:13:30 giles
# Made the length of the kept part of the PWD flexible - a variable
# named near the beginning of the script.
#
# Revision 1.1 1999/06/06 18:02:35 giles
# Initial revision
#function prompt_command {
# How many characters of the $PWD should be kept
local pwd_length=30
# Create TotalMeg variable: sum of visible file sizes in current directory
local TotalBytes=0
for Bytes in $(ls -l | grep "^-" | cut -c30-41)
do
let TotalBytes=$TotalBytes+$Bytes
done
TotalMeg=$(echo -e "scale=3 \nx=$TotalBytes/1048576\n if (x<1) {print \"0\"} \n
print x \nquit" | bc)# Count visible files:
let files=$(ls -l | grep "^-" | wc -l | tr -d " ")
let hiddenfiles=$(ls -l -d .* | grep "^-" | wc -l | tr -d " ")
let executables=$(ls -l | grep ^-..x | wc -l | tr -d " ")
let directories=$(ls -l | grep "^d" | wc -l | tr -d " ")
let hiddendirectories=$(ls -l -d .* | grep "^d" | wc -l | tr -d " ")-2if [ $(echo -n $PWD | wc -c | tr -d " ") -gt $pwd_length ]
then
newPWD="...$(echo -n $PWD | sed -e "s/.*\(.\{$pwd_length\}\)/\1/")"
else
newPWD="$(echo -n $PWD)"
fi
}PROMPT_COMMAND=prompt_command
function rprom {
local BLUE="\[\033[0;34m\]"
local LIGHT_GRAY="\[\033[0;37m\]"
local LIGHT_GREEN="\[\033[1;32m\]"
local LIGHT_BLUE="\[\033[1;34m\]"
local LIGHT_CYAN="\[\033[1;36m\]"
local YELLOW="\[\033[1;33m\]"
local WHITE="\[\033[1;37m\]"
local RED="\[\033[0;31m\]"
local NO_COLOUR="\[\033[0m\]"case $TERM in
xterm*)
TITLEBAR='\[\033]0;\u@\h:\w\007\]'
;;
*)
TITLEBAR=""
;;
esacPS1="$TITLEBAR\
$BLUE[$RED\$(date +%H%M)$BLUE]\
$BLUE[$RED\u@\h$BLUE]\
$BLUE[\
$LIGHT_GRAY\${files}.\${hiddenfiles}-\
$LIGHT_GREEN\${executables}x \
$LIGHT_GRAY(\${TotalMeg}Mb) \
$LIGHT_BLUE\${directories}.\
\${hiddendirectories}d\
$BLUE]\
\n\
$BLUE[$RED\$newPWD$BLUE]\
$WHITE\$\
\
$NO_COLOUR "
PS2='> '
PS4='+ '
}
Last modified: November 08, 2019