UsingMac.com

Mac Tricks and Tips, Wallpapers and Applications for Mac Users

Twiddle with Terminal Command Prompt

Advertisements

The tendency to use Terminal seems obvious to most Mac users. Unlike many others, today we are going to go through some fun stuffs with Mac Unix Command, with the way we use Terminal.

Simplifying Terminal Command Prompt

We are going to customize our command prompt and change it to a more humble, neat appearance. Just follow our instructions and you can have a simplified command prompt like ours.

Simple Terminal

  1. Open Terminal
  2. Execute Terminal command nano .bash_profile to open the file
  3. Copy the following lines and put inside
  4. function prompt {
      local GRAY="\[\033]0;37m\]"
      export PS1="\$${GRAY} ${WHITE}"
    }
    prompt
    
  5. Save the file by pressing control-o follow by hitting return key to confirm save path. And then press control-x to exit from the nano
  6. Load the file using following command:
  7. source ~/.bash_profile
    
  8. Now your Terminal should be in simplified form as above

Prefixing Terminal Command Prompt

It's good to have a simplified command prompt, but it's indeed giving the touch of boredom for its monotonous. That's where we can apply our next twist: prefixing command prompt. See screen shot below for teaser.

Terminal Emo

  1. Open Terminal
  2. Execute Terminal command nano .bash_profile to open the file
  3. Copy the following lines and put inside
  4. function prompt {
      local WHITE="\[\033[1;37m\]"
      local GREEN="\[\033[0;32m\]"
      local CYAN="\[\033[0;36m\]"
      export PS1="${WHITE}\$ ${GREEN}Your wish is my command: ${WHITE}"
    }
    prompt
    
  5. Save the file by pressing control-o follow by hitting return key to confirm save path. And then press control-x to exit from the nano
  6. Load the file using following command:
  7. source ~/.bash_profile
    
  8. Now your Terminal should have become your servant

Have you had enough fun with those two twists? Note that in the second twist, you can change the text "Your wish is my command: " to any texts you want.

Decorating Terminal Command Prompt

Obviously, playing around with plain text won't give us long-lasting fun. Let's move on to the next twist, where you can grab user-name, host-name, and even file-path to add as command prompt prefix. Just like ours.

Decorated Terminal

  1. Open Terminal
  2. Execute Terminal command nano .bash_profile to open the file
  3. Copy the following lines and put inside
  4. function prompt {
      local WHITE="\[\033[1;37m\]"
      local GREEN="\[\033[0;32m\]"
      local CYAN="\[\033[0;36m\]"
      export PS1="Doh, ${GREEN}\u${WHITE}, you're inside ${CYAN}\w ${WHITE}: "
    }
    prompt
    
  5. Save the file by pressing control-o follow by hitting return key to confirm save path. And then press control-x to exit from the nano
  6. Load the file using following command:
  7. source ~/.bash_profile
    
  8. \u refers to username
    \h refers to hostname
    \w referes to current file path

If you've noticed, before the change in text color, you could see one of these: ${WHITE}, ${GREEN} or ${CYAN}. Those are the ANSI codes for graphics settings. For creating more creative decorations, check out available ANSI codes here.

If you have any other interesting ideas to twist Terminal command prompt, feel free to post on provided comment box below.

Categories: Tweak, UNIX, Open Source
Tags: Terminal, Tweak, Twist

Subscribe to RSS Leave a Comment (36)

Related Entries

Some articles taken from our resource base, tightly related to current article, to empower you with more knowledge on tweaking the most out of your Mac.

36 Comments

James

Cool, I like the simplified form of $ for my terminal :). Thanks  for the neat tip :D

Chaos

I don't like the simpl $ form. How can I undo this???
Thanks :)

Wendy

To undo it, just go into the .bash_profile, delete all texts inside and save it.

Josso

Thanks for this tip. :) I am using the "Homebrew" theme for the Terminal and thus I needed to change it to green. I do like the more simple form, though I would rather have the path added too. I am using this code:

function prompt {
local GREEN="\[\033[0;32m\]"
local UNDERLINE="\[\033[4;32m\]"
export PS1="${UNDERLINE}\w \$${GREEN}"
}
prompt

And the result is: terminal.png

yene

export PS1='\[\e[1;32m\][\u@\h \W]\$\[\e[0m\] '
or mine export PS1='\[\e[0;37m\][\u]\$\[\e[0m\] '
from ArchLinux - Color_Bash_Prompt

Brandon

This only effects the appearance right?  The terminal will still work the same right?

Wendy

Yes, Brandon. The Terminal will work exactly the same as before make-over :)

Tyler

Cool article! I played around with it some.. here's the final output (shows working directory only in teal): screenshot 

The code:
function prompt { local CYAN="\e[0;36m"
local WHITE='\e[0;37m'
export PS1="\$${CYAN}/\W/: ${WHITE}" }
prompt

Does anyone know how to customize the login message?

(sorry about the earlier posts, hopefully an adminstrator can delete the first ones)

ScottB

OK, great writeup!
One question - the ANSI codes are great, but how would I make the above with the USER in BOLD?  I see the code "Bold on" is "1"
Where would i put this value?

Thanks!

Melinda

I am a voracious user of 'open', but it has limitations. Also people suggesting 'open .' ignore that this will create a .DS_Store file in the directory which this hint implies that Drag.app avoids. Toolchain support to avoid unintentional .DS_Store creation can be very handy at times.

One example where 'open -a' is limited is when you need to drag something into an application, but the operation is more contextual than just dropping anywhere. For example, when an application opens a file dialog to select a file, sometimes it's convenient to drag a file onto the dialog directly rather than traversing the file tree or searching for it. Another example is that I suspect 'open -a' wouldn't do what you hope for dragging into drop zones like iDVD and iMovie have.

viz

Hello, i would like to ask about is there any ways to get back to the default after execute the nano .bash_profile? Just thinking to get back to default instead showing "bash" at the border. :(

Wendy

Hi Viz, just go to your .bash_profile (using nano) and then delete lines of code used for changing your Terminal command prompt display. After you saved the new changes, your display would be reverted back to default.

Brandon

How do I change background to be the transparent black?  These tweaks don't look right on white.

Leandro

Do you know if these changes works with iTerm?

Ajan

Hey, I'm using a 10.5.6, I changed the appearance with the help of Terminal Preferences.
Prefixing is damn great.
And how to I revert back to the normal profile? I mean, without the $ sign, just how it was before.. 

Goomba4001

I'm having an issue with this. I did all the steps correctly, AFAIK.

1. It shows a $ sign, but it doesn't let me type.
2. I hit return, and instead of the dollar sign, it shows a "]0;37m", and then lets me type.
3. I hit return again, and it's a $ sign, and doesn't let me type. The cycle continues...

Goomba4001

Fixed it. I had to write a "local GRAY="\[\033$\]" instead of a "local WHITE="\[\033[1;37m\]"

Ruban

when i type  ".bash_profile"  to undo all changes , my terminal responds  
" ]0;37m .bash_profile
-bash: .bash_profile: command not found
$"
 and I also have the same problem as Goomba4001

Wendy

Hi all, to revert changes, just go into the .bash_profile, delete all texts inside, and save your empty .bash_profile

dog

i did the whole simple $ thing and i dont like it i am used to the org. i have looked at the coments that you have posted and see that you have written and do not know how to get back to the .bash_profile! can you please help me?

Ajan

guys, everything that wendy has mentioned in the article works perfect.
All we need to do is, copy paste them. It would be easier. :)

[cookie]

Hi Wendy! can you please share with us how we can  change the terminal  background to be the transparent black? ( as the way you have yours)
thank you!

Ahmed Masud

OK so I see that some  people are having simple issues with the ANSI codes in PS1 settings in bash.

Chances are you are having trouble because you mistyped something, like a missing quote or using the wrong quotation marks - there is indeed a difference between " and ' and how they are interpreted by the shell. 


In case you have trouble typing commands ....

Well if you are having trouble actually typing commands at the command prompt then you should remove the .bash_profile from your home directory (notice that there is a period at the beginning of the file). To do this, start the Terminal application, and from the File Menu select New Command.
In the dialog box type:

sh

and click on Run

this will start a shell WITHOUT loading your .bash_profile

You can now delete the .bash_profile by typing

rm ~/.bash_profile

Of course this would be the time to read up on how PS prompts actually work :-) so i would suggest reading up on bash ...


Locally, on your terminal, you can type:

man bash

To get the manual page for bash.

Of course if you want to read up on how man works ... you should type

man man

While you are reading the manual page on bash you will notice that you have a : at the bottom of the screen. You are in the pager ( a program that lets you view text files). Here arrow keys will work to scroll up and down (mouse will not, you are in the terminal), use 'q' to quit out of the manual page, use '?' to view the other keys you can use :-),


For setting all the uses of PS values search for PROMPTING in the bash manual page, (notice capitalization). To search for something in the manual page type a slash (/) and the phrase you are searching for. So, for PROMPTING you would type:

/PROMPTING

Please notice that you are doing this while the bash manual page is open.

Hope that this will get you going :-) on the internals of shell and the power that all your macs posses. A fun place to read up on a shell primer is to have a look at the Bash Scripting Primer

(No connection to me :-)


Hope this helps and that you have fun with it.

Shaun

Hit cmd+, to bring up the preferences pane, then go to settings and choose 'Pro'. Be sure to hit the 'Default' button at the bottom to ensure that all future terminal windows are opened in this style.

I hope that helped.

Jason

My prompt which has colored seperators and a stack depth of up to 4. Follow the same instructions as above to put the following in your .bash_profile 

# Function that returns the last n path components of the specified path after
# replacing $HOME with ~.  Call like:
#     pathComponents path n nameColor seperatorColor
function pathComponents
{
	echo `python -c\
	"import string,re;   pth=re.sub('^$HOME','~',r\"$1\",1);   n = string.atoi(r\"$2\");   nc=r\"$3\";   sc=r\"$4\";\
	print nc + string.join(pth.split('/')[-n:], sc + '/' + nc);"`
}

function myPromptCommand {
	local noColor='\[\033[0;39m\]' # No Color
	local red='\[\033[0;31m\]'
	local green='\[\033[0;32m\]'
	local brown='\[\033[0;33m\]'
	local blue='\[\033[0;34m\]'
	local newPWD=`pathComponents "\${PWD}" 4 \${blue} \${red}`	# the trimed colored path
	echo -ne "\033]0;${HOSTNAME%%.*}:${PWD/$HOME/~}\007"		# this sets the title
	export PS1="${noColor}[${green}\h${noColor}:${newPWD}${noColor}] \$ "
}

PROMPT_COMMAND=myPromptCommand	# Change the title of each window, and PS1 to reflect where we are

Mr.body

I tried changing the prefix on the command prompt and its really cool. the only problem is that I can't seem to reset it back to the way it was. I tried deleting all the .nano text but it doesn't seem to do any good when I run it. Any help would be great. Thanks!

thomas sabo

Honestly, I've always been more of a fan of just putting the monitor to sleep than screen savers. Sure they look pretty awesome, but if you're sitting at your computer, are you really doing so with the screen saver on?Good luck for the dates. It has been some times since we last heard about the next tour. I hope they can run it accordingly now.iY5WynMRT8iHhXlh

headphones

Honestly, I've always been more of a fan of just putting the monitor to sleep than screen savers. Sure they look pretty awesome, but if you're sitting at your computer, are you really doing so with the screen saver on?Good luck for the dates. It has been some times since we last heard about the next tour. I hope they can run it accordingly now.jqLr3TJBKspodK3N

thomas sabo

I like these things, every time I see a little bit excited, especially 
thomas sabo uk even more exciting, to be honest I like thomas sabo of these things!

genius

Honestly, I've always been more of a fan of just putting the monitor to sleep than screen savers. Sure they look pretty awesome, but if you're sitting at your computer, are you really doing so with the screen saver on?Good luck for the dates. Property Finder

malikseo

Honestly, I've always been more of a fan of just putting the monitor to sleep than screen savers. Sure they look pretty awesome, but if you're sitting at your computer, are you really doing so with the screen saver on?Good luck for the dates. Forex Robots

Poko

Je suis profondément reconnaissant d'éclairer, et, surtout, juste à temps. Ишемический инсульт Il suffit de penser, six ans déjà dans un Internet, mais je crois que c'est la première fois que j'ai entendu. Лечение суставов Bonjour à tous, J'ai l'obtention du diplôme . . . . . et dans mon temps libre, j'aime surfer sur le net pour les nouvelles mises à jour de diverses choses dans le monde

Jake Wand

http://jakewand.wordpress.com

Stephen Soos

Le rapport du lecteur avec l'écrivain serait un beau sujet de débat, je trouve. Car si, comme vous, je pense incontournables silence et intimité qui les lient, d'autres dimensions, subtiles, se manifestent lors de rencontres et de partages que j'affectionne et prise, comme vous.
Stephen Soos

Polk

La perception des enfants diffère de l'adulte. Аскариды En plus de DVD intitulé "Alice à travers le miroir", vous pouvez acheter beaucoup d'autres DVD Eh bien au traitement par des méthodes de thérapie physique pour les points de déclenchement Приобрести ДЭНАС

vikasjain

I tried changing the prefix on the command prompt and its really cool.....))
NIT Rourkela 2011 Admission

Leave a Comment