Linux-tips

Any donation is very welcome
Fork me on GitHub

I. Linux tips

7. Some bash tips

I know there are other (better) shells, but bash is certainly the most common one so I'll show tips for it! You can make all the changes that'll be presented permanent by adding them into the file ".bashrc".

Aliases

Quite simple, I guess everyone knows how it works. To make it simple:

alias [alias_name]="[command]"

Which gives:

alias ll="ls -l"

Aliases can use other aliases as well:

alias ls="ls --color=auto"
alias ll="ls -l" # so here, "ls" will become "ls --color=auto"

And I think it's more or less all there is to say for this part.

History

Command history can have some really nice features. For example, you use oftenly the "ls" command and you'd prefer that it wouldn't get reentered in the history? This is possible. Just do the following:

export HISTCONTROL=erasedups

And so, if the command you just entered is already inside your history, the old occurence will be removed.

Prompt

To change your shell prompt, you have to change PS1 variable (there is also PS2, PS3 and PS4, but only PS1 and PS2 are really used). Example:

export PS1="> "

And now your prompt should be "> ".

Nice right? Now what about displaying your name and the current directory?

export PS1="\u @ \w > "

Just like you certainly guessed, "\u" is to display the current user and "\w" is for the current directory.

A lot of other "tools" like this are available. For example, you can also see what was the value returned by the last executed command with "$?". Example:

export PS1="\$? > "
export PS1='$? > ' # this line is the same as the previous one, the difference is that the simple quote text isn't interpreted and "$" won't give struggles.

Just look around on the Internet what flags bash provides.

Now, let's see how to put some colors! First, test this:

export PS1='\[\033[01;32m\]Hello!\[\033[00m\]> ' # and use simple quotes!

As you can see, "Hello!" is green. For more information about colors, take a look to "man console_codes". In our previous example, '[\033[01;32m]' means bold green ("01" is for bold and "32" is for green"), '[\033[00m]' is for going back to normal. If you don't put it at the end of your prompt, the text you'll enter will have this color as well.

Now you know the basics for some bash tips. Before leaving you, I'll show you the prompt I'm using:

"\[\033[01;31m\]\u\[\033[01;32m\]@\[\033[01;33m\]\$PWD >\[\033[00m\] " # ("\h" stands for hostname)

Redirect all outputs

It can be convenient to get all outputs (stdio and stderr) in one stream. You can do it with |&. Example:

> find . |& grep "not found"