As I mention in the introduction to The Linux Command Line, the command line is a long lasting skill. It's quite possible that a script that you wrote ten years ago still works perfectly well today. But even so, every few years the GNU Project releases a new version of bash. While I was writing the book, version 3.2 was the predominate version found in Linux distributions. In February of 2009 however a new major version of bash (4.0) appeared and it began to show up in distributions last fall. Today the current version of bash is 4.1 and it, too, is beginning to show up in distributions such as Ubuntu 10.04 and (I presume, since I haven't checked yet) Fedora 13.
So what's new in bash? A bunch of things, though most of them tend to be rather small. In this series we will look at features that, I feel, are of the most use to ordinary shell users starting with a couple of the small ones.
Finding Your Version
How do you know if you are using the latest, greatest bash? By issuing a command of course:
me@linuxbox: ~$ echo $BASH_VERSION
4.1.2(1)-release
bash maintains a shell variable called BASH_VERSION that always contains the version number of the shell in use. The example above is from my Ubuntu 10.04 test machine and it dutifully reveals that we are running bash version 4.1.2.
Better help
The help command, which is used to display documentation for the shell's builtin commands, got some much needed attention in the new version of bash. The command has some new options and the help text itself has been reformatted and improved. For example, here is the result of the help cd command in bash 3.2:
bshotts@twin2:~$ help cd
cd: cd [-L|-P] [dir]
Change the current directory to DIR. The variable $HOME is the
default DIR. The variable CDPATH defines the search path for
the directory containing DIR. Alternative directory names in CDPATH
are separated by a colon (:). A null directory name is the same as
the current directory, i.e. `.'. If DIR begins with a slash (/),
then CDPATH is not used. If the directory is not found, and the
shell option `cdable_vars' is set, then try the word as a variable
name. If that variable has a value, then cd to the value of that
variable. The -P option says to use the physical directory structure
instead of following symbolic links; the -L option forces symbolic links
to be followed.
The same command in bash 4.1:
bshotts@twin7:~$ help cd
cd: cd [-L|-P] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed
-P use the physical directory structure without following symbolic
links
The default is to follow symbolic links, as if `-L' were specified.
Exit Status:
Returns 0 if the directory is changed; non-zero otherwise.
As you can see, the output is more "man page-like" than the previous version, as well as better written. help also includes two new options, -d which displays a short description of the command and the -m option which displays the help text in full man page format.
New Redirections
It is now possible to combine both standard output and standard error from a command and append it to a file using this form:
command &>> file
Likewise, it is possible to pipe the combined output streams using this:
command1 |& command2
where the standard output and standard error of command1 is piped into the standard input of command2. This form may be used in place of the traditional form:
command1 2>&1 | command2
Further Reading
Here are some change summaries for the 4.x version of bash:
Other installments in this series: 1 2 3 4
Tuesday, April 6, 2010
Thursday, April 1, 2010
Script: average
A few weeks ago, I was cruising the Ubuntu forums and came across a question from a poster who wanted to find the average of a series of floating-point numbers. The numbers were extracted from some other command and were output in a column. He wanted a command line incantation that would take the column of numbers and return the average. Several people answered this query with clever one-line solutions, however I thought that this problem would be a good task for a script. Using a script, one could have a solution that was a little more robust and general purpose. I wrote the following script, presented here with line numbers:
1 #!/bin/bash
2
3 # average - calculate the average of a series of numbers
4
5 # handle cmd line option
6 if [[ $1 ]]; then
7 case $1 in
8 -s|--scale) scale=$2 ;;
9 *) echo "usage: average [-s scale]" >&2
10 exit 1 ;;
11 esac
12 fi
13
14 # construct instruction stream for bc
15 c=0
16 { echo "t = 0; scale = 2"
17 [[ $scale ]] && echo "scale = $scale"
18 while read value; do
19
20 # only process valid numbers
21 if [[ $value =~ ^[-+]?[0-9]*\.?[0-9]+$ ]]; then
22 echo "t += $value"
23 ((++c))
24 fi
25 done
26
27 # make sure we don't divide by zero
28 ((c)) && echo "t / $c"
29 } | bc
This script takes a series of numbers from standard input and prints the result. It is invoked as follows:
average -s scale < file_of_numbers
where scale is an integer containing the desired number of decimal places in the result and file_of_numbers is a file containing the series of number we desire to average. If scale is not specified, then the default value of 2 is used.
To demonstrate the script, we will calculate the average size of the programs in the /usr/bin directory:
me@linuxbox:~$ stat --format "%s" /usr/bin/* | average
81766.66
The basic idea behind this script is that it uses the bc arbitrary precision calculator program to figure out the average. We need to use something like bc, because arithmetic expansion in the shell can only handle integer math.
To perform our calculation, we need to construct a series of instructions and pipe them into bc. This task comprises the bulk of our script. In order to do something that complicated, we employ a shell feature known as a group command. Starting with line 16 and ending with line 29 we capture all of the standard output and consolidate it into a single stream. That is, all of the standard output produced by the commands on lines 16-29 is treated as though it is a single command and piped into bc on line 29.
We'll look at our group command piece by piece. As you know, an average is calculated by adding up a series of numbers and dividing the sum by the number of entries. In our case, the number of entries is stored in the variable c and the sum is stored (within bc) in the variable t. We start our group command (line 16) by passing some initial values to bc. We set the initial value of the bc variable t to zero and the value of scale to our default value of two (the default scale of bc is zero).
On line 17, we evaluate the scale variable to see if the command line option was used and if so, pass that new value to bc.
Next, we start a while loop that reads entries from our standard input. Each iteration of the loop causes the next entry in the series to be assigned to the variable value.
Lines 20-24 are interesting. Here we test to see if the string contained in value is actually a valid floating point number. To do this, we employ a regular expression that will only match if the number is properly formatted. The regular expression says, to match, value may start with a plus or minus sign, followed by zero or more numerals, followed by an optional decimal point, and ending with one or more numerals.. If value passes this test, an instruction is inserted into the stream telling bc to add value to t (line 22) and we increment c (line 23), otherwise value is ignored.
After all of the numbers have been read from standard input, it's time to perform the calculation, First, we test to see that we actually processed some numbers. If we did not, then c would equal zero and the resulting calculation would cause a "division by zero" error, so we test the value of c and only if it is not equal to zero we insert the final instruction for bc.
This script would make a good starting point for a series of statistical programs. The most significant design weakness of the script as written is that it fails to check that the value supplied to the scale option is really an integer. That's an improvement I will leave to my faithful readers...
Further Reading
The following man pages:
1 #!/bin/bash
2
3 # average - calculate the average of a series of numbers
4
5 # handle cmd line option
6 if [[ $1 ]]; then
7 case $1 in
8 -s|--scale) scale=$2 ;;
9 *) echo "usage: average [-s scale]" >&2
10 exit 1 ;;
11 esac
12 fi
13
14 # construct instruction stream for bc
15 c=0
16 { echo "t = 0; scale = 2"
17 [[ $scale ]] && echo "scale = $scale"
18 while read value; do
19
20 # only process valid numbers
21 if [[ $value =~ ^[-+]?[0-9]*\.?[0-9]+$ ]]; then
22 echo "t += $value"
23 ((++c))
24 fi
25 done
26
27 # make sure we don't divide by zero
28 ((c)) && echo "t / $c"
29 } | bc
This script takes a series of numbers from standard input and prints the result. It is invoked as follows:
average -s scale < file_of_numbers
where scale is an integer containing the desired number of decimal places in the result and file_of_numbers is a file containing the series of number we desire to average. If scale is not specified, then the default value of 2 is used.
To demonstrate the script, we will calculate the average size of the programs in the /usr/bin directory:
me@linuxbox:~$ stat --format "%s" /usr/bin/* | average
81766.66
The basic idea behind this script is that it uses the bc arbitrary precision calculator program to figure out the average. We need to use something like bc, because arithmetic expansion in the shell can only handle integer math.
To perform our calculation, we need to construct a series of instructions and pipe them into bc. This task comprises the bulk of our script. In order to do something that complicated, we employ a shell feature known as a group command. Starting with line 16 and ending with line 29 we capture all of the standard output and consolidate it into a single stream. That is, all of the standard output produced by the commands on lines 16-29 is treated as though it is a single command and piped into bc on line 29.
We'll look at our group command piece by piece. As you know, an average is calculated by adding up a series of numbers and dividing the sum by the number of entries. In our case, the number of entries is stored in the variable c and the sum is stored (within bc) in the variable t. We start our group command (line 16) by passing some initial values to bc. We set the initial value of the bc variable t to zero and the value of scale to our default value of two (the default scale of bc is zero).
On line 17, we evaluate the scale variable to see if the command line option was used and if so, pass that new value to bc.
Next, we start a while loop that reads entries from our standard input. Each iteration of the loop causes the next entry in the series to be assigned to the variable value.
Lines 20-24 are interesting. Here we test to see if the string contained in value is actually a valid floating point number. To do this, we employ a regular expression that will only match if the number is properly formatted. The regular expression says, to match, value may start with a plus or minus sign, followed by zero or more numerals, followed by an optional decimal point, and ending with one or more numerals.. If value passes this test, an instruction is inserted into the stream telling bc to add value to t (line 22) and we increment c (line 23), otherwise value is ignored.
After all of the numbers have been read from standard input, it's time to perform the calculation, First, we test to see that we actually processed some numbers. If we did not, then c would equal zero and the resulting calculation would cause a "division by zero" error, so we test the value of c and only if it is not equal to zero we insert the final instruction for bc.
This script would make a good starting point for a series of statistical programs. The most significant design weakness of the script as written is that it fails to check that the value supplied to the scale option is really an integer. That's an improvement I will leave to my faithful readers...
Further Reading
The following man pages:
- bc
- bash (the "Compound Commands" section, covers group commands and the [[]] and (()) compound commands)
- Chapter 20 (regular expressions)
- Chapter 28 (if command, [[]] and (()) compound commands and && and || control operators)
- Chapter 29 (the read command)
- Chapter 30 (while loops)
- Chapter 35 (arithmetic expressions and expansion, bc program)
- Chapter 33 (positional parameters)
- Chapter 37 (group commands)
Tuesday, March 30, 2010
Site News: LinuxCommand.org Turns 10!
LinuxCommand.org is 10 years old! The site first went live in March 2000. Since then I've had about 3.2 million visitors (at least according to the statistics at SourceForge where I'm hosted), received many kind emails from my readers, written a book, distributed a lot of scripts, and been mirrored all around the world.
In the coming year, I hope to update the tutorials on the site. Much of the text, believe it or not, dates back to the beginning of the site, another testament to the enduring value of learning the command line. But even so, the tutorials are getting a little outdated and my own knowledge has grown considerably over the last ten years as well.
As you may have noticed, this blog has been pretty busy and I have settled into a routine of posting twice a week (on Tuesdays and Thursdays) and I have many more topics in mind to cover. And there is always the book to improve. I've even toyed with writing another one...
Anyway, I want to thank everyone for their kind words of encouragement and support. I know I don't always respond to each email that I receive, but I do try. Speaking of support, you can support the work here at LinuxCommand.org by purchasing your very own printed copy of my book. I've donated money to a number of free and open source software projects over the years and continue to "pay for my software" by producing this site and performing software testing on projects that interest me.
Thanks to everyone for ten great years!
Further Reading
A look at LinuxCommand.org over the years, courtesy of the Wayback Machine:
The traffic history of LinuxCommand.org:
In the coming year, I hope to update the tutorials on the site. Much of the text, believe it or not, dates back to the beginning of the site, another testament to the enduring value of learning the command line. But even so, the tutorials are getting a little outdated and my own knowledge has grown considerably over the last ten years as well.
As you may have noticed, this blog has been pretty busy and I have settled into a routine of posting twice a week (on Tuesdays and Thursdays) and I have many more topics in mind to cover. And there is always the book to improve. I've even toyed with writing another one...
Anyway, I want to thank everyone for their kind words of encouragement and support. I know I don't always respond to each email that I receive, but I do try. Speaking of support, you can support the work here at LinuxCommand.org by purchasing your very own printed copy of my book. I've donated money to a number of free and open source software projects over the years and continue to "pay for my software" by producing this site and performing software testing on projects that interest me.
Thanks to everyone for ten great years!
Further Reading
A look at LinuxCommand.org over the years, courtesy of the Wayback Machine:
The traffic history of LinuxCommand.org:
Thursday, March 25, 2010
byobu
One of the features I have discovered during my testing of the Ubuntu10.04 beta is a nifty program called byobu, a slick wrapper for the screen terminal multiplexing program. If you are unfamiliar with screen, please see the final installment of my Building An All-Text Linux Workstation series.
byobu was introduced in Ubuntu 09.10 and continues in 10.04. The name "byobu" comes from a Japanese word meaning "folding screen." Essentially, byobu adds an improved user interface to screen and takes advantage some advanced features in recent screen versions. On a system so equipped, you launch byobu like this:
bshotts@twin7:~$ byobu
and you get a display like this:

We get a screen terminal session with system status notifications at the bottom of the terminal display.
byobu allows the use of function keys in addition to the usual Ctrl-a sequences supported by screen. As indicated at the bottom right corner of the terminal, the F9 key invokes a menu:

Function Key Assignments
byobu assigns function keys to perform many of the common operations performed by screen, such as opening new terminal sessions, moving from session to session, and entering scroll back mode. Selecting the "Help" item on the menu displays a map of the program's function key assignments:

Status Notifications
Also of interest is the list of available system indicators which is visible when the "Toggle status notifications" item is selected on the menu:

As you can see this is a pretty big list.
Other Features
It's also possible to create default windows, that is, terminal sessions that appear automatically when you start byobu. This is handy if you have several applications that you want to start when you log in at the terminal.
Further Reading
A Wikipedia article on Japanese folding screens
byobu was introduced in Ubuntu 09.10 and continues in 10.04. The name "byobu" comes from a Japanese word meaning "folding screen." Essentially, byobu adds an improved user interface to screen and takes advantage some advanced features in recent screen versions. On a system so equipped, you launch byobu like this:
bshotts@twin7:~$ byobu
and you get a display like this:
We get a screen terminal session with system status notifications at the bottom of the terminal display.
byobu allows the use of function keys in addition to the usual Ctrl-a sequences supported by screen. As indicated at the bottom right corner of the terminal, the F9 key invokes a menu:
Function Key Assignments
byobu assigns function keys to perform many of the common operations performed by screen, such as opening new terminal sessions, moving from session to session, and entering scroll back mode. Selecting the "Help" item on the menu displays a map of the program's function key assignments:
Status Notifications
Also of interest is the list of available system indicators which is visible when the "Toggle status notifications" item is selected on the menu:
As you can see this is a pretty big list.
Other Features
It's also possible to create default windows, that is, terminal sessions that appear automatically when you start byobu. This is handy if you have several applications that you want to start when you log in at the terminal.
Further Reading
- The screen and byobu man pages
A Wikipedia article on Japanese folding screens
Tuesday, March 23, 2010
Project: Getting Ready For Ubuntu 10.04 - Part 3
Now that Ubuntu 10.04 Beta 1 has been released, it's time to start our work. In this installment we will obtain a copy of Beta 1, make some installation media, install it, and begin our testing.
Getting The Beta 1 Image
This page has links to the ISO images that we will use. Of course, you could just download them from your web browser, but what's the fun in that? Since we are command line junkies here at LinuxCommand.org, we use the command line to download our images. You can do it like this:
me@linuxbox: ~$ wget url
where url is the web address of the ISO image we want to download In my case, I used this command to get the "PC (Intel x86) Desktop CD":
wget http://releases.ubuntu.com/10.04/ubuntu-10.04-beta1-desktop-i386.iso

Creating Installation Media
The next step is making the installation media. I always use re-writable media for this kind of work, so we have to first "blank" our CD, then write the image on it. To do this, we use the wodim program. First, we need to determine what our system calls the CD burner. We can do this with the following command:
me@linuxbox: ~$ wodim --devices
wodim will execute and print a list of the optical media drives it sees. The results will look like this:
wodim: Overview of accessible drives (1 found) :
-------------------------------------------------------------------------
0 dev='/dev/scd0' rwrw-- : 'Optiarc' 'DVD+-RW AD-7200S'
-------------------------------------------------------------------------
On my system, we see that the CD-ROM drive/burner is the device "/dev/scd0". Yours may be different.
insert the re-writable disk into the drive. If your system automatically mounts the disk, unmount it with a command such as this:
me@linuxbox: ~$ sudo umount /dev/scd0
Next, we blank the media with this command:
me@linuxbox: ~$ wodim -vv dev=/dev/scd0 blank=all
The blanking operation will take several minutes. After it completes, we can write the image with this command:
me@linuxbox: ~$ wodim -v dev=/dev/scd0 -data ubuntu-10.04-beta1-desktop-i386.iso
After the write is completed, we need to verify that the disk matches the ISO file. Using this command will do the trick:
me@linuxbox: ~$ md5sum ubuntu-10.04-beta1-desktop-i386.iso /dev/scd0
7ddbfbcfcc562bae2e160695ec820e39 ubuntu-10.04-beta1-desktop-i386.iso
7ddbfbcfcc562bae2e160695ec820e39 /dev/scd0
If the two checksums match, we have a good burn.
Installation
Depending on which variety of 10.04 you have downloaded (desktop, alternate, etc.), the installation procedure should be familiar to any Ubuntu user. The live desktop version differs from previous versions in that it no longer prompts you for running live or installing immediately after booting, rather you are forced to wait (and wait...) for the entire live CD to come up before being prompted with a graphical screen. Not an improvement, in my opinion.
After installation, the first thing we do is open a terminal and perform an update to the system using the following commands:
sudo apt-get update
sudo apt-get upgrade
Be aware that during the testing period, the Ubuntu team releases a steady stream of updates. It is not unusual for a hundred or more package updates to be released each day during periods of heavy development. I actually created this alias and put it in my .bashrc file on the test machine:
alias update='sudo apt-get update && sudo apt-get upgrade'
Now I just have to type "upgrade" to bring the machine up to date.
Paying For Your Software - Testing
This is a theme I have touched on before. If you have been an avid Linux consumer, you should consider becoming an avid Linux producer. Great software doesn't write itself. There are many ways you can help build the future of computing (and by the way, cheer leading is not one of them). One way is by performing good software testing. I have included some links (below) that document some of the tools and techniques that Ubuntu recommend for testing and bug reporting.
Meanwhile, Back At The Ranch...
Work continues on cleaning up the production systems in preparation for the upgrade. I also performed live CD tests on both systems to look for possible hardware incompatibilities. I haven't found any on the desktop system (yet) and the laptop has some minor video issues when booting. Work will continue.
Further Reading
10.04 Beta 1 Release Notes:
Some advice on CD/DVD burning:
Tips and techniques for software testers:
Getting The Beta 1 Image
This page has links to the ISO images that we will use. Of course, you could just download them from your web browser, but what's the fun in that? Since we are command line junkies here at LinuxCommand.org, we use the command line to download our images. You can do it like this:
me@linuxbox: ~$ wget url
where url is the web address of the ISO image we want to download In my case, I used this command to get the "PC (Intel x86) Desktop CD":
wget http://releases.ubuntu.com/10.04/ubuntu-10.04-beta1-desktop-i386.iso
Creating Installation Media
The next step is making the installation media. I always use re-writable media for this kind of work, so we have to first "blank" our CD, then write the image on it. To do this, we use the wodim program. First, we need to determine what our system calls the CD burner. We can do this with the following command:
me@linuxbox: ~$ wodim --devices
wodim will execute and print a list of the optical media drives it sees. The results will look like this:
wodim: Overview of accessible drives (1 found) :
-------------------------------------------------------------------------
0 dev='/dev/scd0' rwrw-- : 'Optiarc' 'DVD+-RW AD-7200S'
-------------------------------------------------------------------------
On my system, we see that the CD-ROM drive/burner is the device "/dev/scd0". Yours may be different.
insert the re-writable disk into the drive. If your system automatically mounts the disk, unmount it with a command such as this:
me@linuxbox: ~$ sudo umount /dev/scd0
Next, we blank the media with this command:
me@linuxbox: ~$ wodim -vv dev=/dev/scd0 blank=all
The blanking operation will take several minutes. After it completes, we can write the image with this command:
me@linuxbox: ~$ wodim -v dev=/dev/scd0 -data ubuntu-10.04-beta1-desktop-i386.iso
After the write is completed, we need to verify that the disk matches the ISO file. Using this command will do the trick:
me@linuxbox: ~$ md5sum ubuntu-10.04-beta1-desktop-i386.iso /dev/scd0
7ddbfbcfcc562bae2e160695ec820e39 ubuntu-10.04-beta1-desktop-i386.iso
7ddbfbcfcc562bae2e160695ec820e39 /dev/scd0
If the two checksums match, we have a good burn.
Installation
Depending on which variety of 10.04 you have downloaded (desktop, alternate, etc.), the installation procedure should be familiar to any Ubuntu user. The live desktop version differs from previous versions in that it no longer prompts you for running live or installing immediately after booting, rather you are forced to wait (and wait...) for the entire live CD to come up before being prompted with a graphical screen. Not an improvement, in my opinion.
After installation, the first thing we do is open a terminal and perform an update to the system using the following commands:
sudo apt-get update
sudo apt-get upgrade
Be aware that during the testing period, the Ubuntu team releases a steady stream of updates. It is not unusual for a hundred or more package updates to be released each day during periods of heavy development. I actually created this alias and put it in my .bashrc file on the test machine:
alias update='sudo apt-get update && sudo apt-get upgrade'
Now I just have to type "upgrade" to bring the machine up to date.
Paying For Your Software - Testing
This is a theme I have touched on before. If you have been an avid Linux consumer, you should consider becoming an avid Linux producer. Great software doesn't write itself. There are many ways you can help build the future of computing (and by the way, cheer leading is not one of them). One way is by performing good software testing. I have included some links (below) that document some of the tools and techniques that Ubuntu recommend for testing and bug reporting.
Meanwhile, Back At The Ranch...
Work continues on cleaning up the production systems in preparation for the upgrade. I also performed live CD tests on both systems to look for possible hardware incompatibilities. I haven't found any on the desktop system (yet) and the laptop has some minor video issues when booting. Work will continue.
Further Reading
10.04 Beta 1 Release Notes:
Some advice on CD/DVD burning:
- https://help.ubuntu.com/community/BurningIsoHowto
- https://help.ubuntu.com/community/CdDvd/Burning
- Chapter 16 of The Linux Command Line covers various kinds of storage media.
Tips and techniques for software testers:
- https://wiki.ubuntu.com/Testing
- https://help.ubuntu.com/community/ReportingBugs
- https://wiki.ubuntu.com/DebuggingProcedures
Subscribe to:
Posts (Atom)
