Bash

Article by on June 1, 2012, last modified on August 2, 2014

About

Bash is a UNIX shell that is awesome. Bash is a "command processor" that allows you to type text commands to a computer, or even a remote computer using programs like SSH. Bash stands for "Bourne-Again SHell", the Bourne shell (sh) being a predecessor and competitor to Bash.

Debugging

Run a Harmless Non-Zero Exit Status Command

Let's say you are writing a bash script and want to handle the case where a command returns a non-zero exit status, you can test that case using a harmless command that returns a non-zero exit status. For example,

cat nosuchfile 2>/dev/null
if [ $? -ne 0 ]
then
    echo "It failed!"
fi

Then, once you have written the code for that case, you can simply replace the command with the one you actually want to use.

The idea came from an irrelevant comment on StackOverflow.

Control Structures

This is the best reference for "if" statements: http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Tip: Make sure you have a space between comparison operators. Basically, just put spaces between everything on your conditional line, such as:

if [ -z "$1" ] || [ "$a" == "$b" ]

Screen

How to run a command in the background?

As a StackOverflow comment notes, you can use the screen command:

$ screen

Then type whatever command you want to run.

$ /usr/bin/java -jar /usr/local/bin/selenium-server-standalone-2.21.0.jar &

Then hit CTRL+D or type exit and it will return you back to the previous "screen".

List of Colors

A great article on ArchLinux.org lists all the bash colors, but doesn't list their RGB equivalents. However, Edward Livingston-Blade published a list of colors and their bash code, but not the bash syntax. He notes that the colors aren't the same for every environment since they aren't defined as RGB colors by the system. He also lists some great bash snippets to show the colors. Nonetheless, here is a list of colors in a table, which I find convenient:

Color Bash Syntax RGB Color
Regular Fonts
Black
\e[0;30m
#000000
Red
\e[0;31m
#AA0000
Green
\e[0;32m
#00AA00
Yellow
\e[0;33m
#AA5500
Blue
\e[0;34m
#0000AA
Purple
\e[0;35m
#AA00AA
Cyan
\e[0;36m
#00AAAA
White
\e[0;37m
#AAAAAA
Bold Fonts
Black
\e[1;30m
#000000
Red
\e[1;31m
#FF5555
Green
\e[1;32m
#55FF55
Yellow
\e[1;33m
#FFFF55
Blue
\e[1;34m
#5555FF
Purple
\e[1;35m
#FF55FF
Cyan
\e[1;36m
#55FFFF
White
\e[1;37m
#FFFFFF
Underlined Fonts
Black
\e[4;30m
#000000
Red
\e[4;31m
#AA0000
Green
\e[4;32m
#00AA00
Yellow
\e[4;33m
#AA5500
Blue
\e[4;34m
#0000AA
Purple
\e[4;35m
#AA00AA
Cyan
\e[4;36m
#00AAAA
White
\e[4;37m
#AAAAAA
Backgrounds
Black
\e[40m
#000000
Red
\e[41m
#AA0000
Green
\e[42m
#00AA00
Yellow
\e[43m
#AA5500
Blue
\e[44m
#0000AA
Purple
\e[45m
#AA00AA
Cyan
\e[46m
#00AAAA
White
\e[47m
#AAAAAA
Other
Text Reset
\e[0m

References

https://wiki.archlinux.org/index.php/Color_Bash_Prompt
https://bbs.archlinux.org/viewtopic.php?id=51818
http://linuxgazette.net/issue51/livingston-blade.html
http://webhome.csc.uvic.ca/~sae/seng265/fall04/tips/s265s047-tips/bash-using-colors.html

Dot Files

Many people have their "dot files" listed on GitHub. Here is a link to mine: https://github.com/josephdpurcell/dotfiles.

Create a custom prompt: http://bashrcgenerator.com/

Shortcuts

http://www.howtogeek.com/?post_type=post&p=44997

The above link has a very amusing command:

$ cat /dev/urandom | hexdump -C | grep "ca fe"

Use Ouptput of Previous Command as Argument

Let's say you want to use the output of a previous command as an argument for the current command. You can use the magical double bang, as a StackOverflow comment shows. Here is an example:

$ which git
/opt/local/bin/git
$ `!!` status
# On branch master
nothing to commit (working directory clean)

Or, maybe you are looking for a file to edit, you may do something like:

$ sudo find /etc/* -name "php.ini"
/etc/php.ini
$ vim `!!`

There are a number of ways to accomplish this same idea, as is discussed in a StackOverflow thread.

Pipes and Redirects

Options for Piping and Redirecting

First, read Peteris Krumins' article "Bash One-Liners Explained, Part III: All about redirections". Then, in the future you can use this for reference:

Option 1: >

$ cat file.txt > file2.txt

Option 2: tee

$ cat file.txt | tee file.txt

http://linux.101hacks.com/unix/tee-command-examples/

Option 3: mkfifo

"Using Named Pipes (FIFOs) with Bash" (Linux Journal)

"Introduction to Named Pipes" (Linux Journal)

Option 4: Named Pipes

http://www.hollenback.net/NamedPipesInBash

Switching stderr to stdout

Use 2>&1, i.e.

$ find / -name "file.txt" 2>&1

http://stackoverflow.com/questions/818255/in-the-bash-shell-what-is-21

Piping stderr and stdout to file

Use &>, i.e.

$ find / -name "file.txt" &> output.txt

http://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-3.html

Further Reading

Arrays

http://www.linuxjournal.com/content/bash-arrays

Loop Through an Array

http://www.cyberciti.biz/faq/bash-for-loop-array/

http://www.cyberciti.biz/faq/bash-iterate-array/

http://www.thegeekstuff.com/2010/06/bash-array-tutorial/

Loop Through Files in a Directory

http://www.cyberciti.biz/faq/bash-loop-over-file/

http://www.cyberciti.biz/faq/unix-loop-through-files-in-a-directory/

Splitting a String as an Array

Say you have a string called $str and it is delimited by an underscore, you can split it apart and access it as an array using the following method:

local arr=(`echo $str | tr "_" "\n"`)
local x1=${flag[0]}
local x2=${flag[1]}
echo $x1
echo $x2

For more examples and other methods of splitting an array, see "bash: split string to array" post on Short IT Recipes.

String Manipulation

http://tldp.org/LDP/abs/html/string-manipulation.html

Handling Inputs

Inputs are space delimited. Each input is then saved as $1, $2, $3, ..., $n. The array of all inputs is $@. However, if you want a full blown CLI, you will want to use a tool to handle these parameters. The most common is getopt and getopts.

Colin Zwiebel has a concise list of relevant links: http://clogin.posterous.com/great-bash-scripting-getopts-example. They are worth going through. I found the following article the most helpful: http://techpatterns.com/forums/about1138.html.

Further Reading

http://mmb.pcb.ub.es/~carlesfe/unix/tricks.txt

Older Articles »