331496a512057ce2e8fbd24f77bd437b95167750
[swc-modular-shell.git] / shell / Readme.md
1 # The Shell
2
3 **Material by Paul Wilson, Milad Fatenejad, Sasha Wood, and Radhika Khetani**
4
5 # What is the shell how do I access the shell?
6
7 The *shell* is a program that presents a command line interface
8 which allows you to control your computer using commands entered
9 with a keyboard instead of controlling graphical user interfaces
10 (GUIs) with a mouse/keyboard combination.
11
12 Use a browser to open the tutorial on github, located at:
13     https://github.com/USERNAME/boot-camps/tree/YYYY-MM-PLACE
14
15 Click on the directory named `shell`.
16
17 A *terminal* is a program you run that gives you access to the
18 shell. There are many different terminal programs that vary across
19 operating systems.
20          
21 There are many reasons to learn about the shell. In my opinion, the
22 most important reasons are that: 
23
24 1.  It is very common to encounter the shell and
25     command-line-interfaces in scientific computing, so you will
26     probably have to learn it eventually 
27
28 2.  The shell is a really powerful way of interacting with your
29     computer. GUIs and the shell are complementary - by knowing both
30     you will greatly expand the range of tasks you can accomplish with
31     your computer. You will also be able to perform many tasks more
32     efficiently.
33
34 The shell is just a program and there are many different shell
35 programs that have been developed. The most common shell (and the one
36 we will use) is called the Bourne-Again SHell (bash). Even if bash is
37 not the default shell, it is usually installed on most systems and can be
38 started by typing `bash` in the terminal. Many commands, especially a
39 lot of the basic ones, work across the various shells but many things
40 are different. I recommend sticking with bash and learning it well.
41 ([Here is a link for more information](http://en.wikipedia.org/wiki/Bash_(Unix_shell))
42
43 To open a terminal, just single click on the "Terminal" icon on the
44 Desktop.
45
46 # The Example: Manipulating Experimental Data Files
47
48 We will spend most of our time learning about the basics of the shell
49 by manipulating some experimental data from a hearing test. To get
50 the data for this test, you will need internet access. Just enter the
51 command:
52
53     git clone -b YYYY-MM-PLACE https://github.com/USERNAME/boot-camps.git
54
55 This command will grab all of the data needed for this workshop from
56 the internet.  (We will talk about the `git` command later in the
57 workshop.)
58
59 # Let's get started
60
61 One very basic command is `echo`. This command just prints text to
62 the terminal. Try the command:
63
64     echo Hello, World
65
66 Then press enter. You should see the text "Hello, World" printed back
67 to you. The echo command is useful for printing from a shell script,
68 for displaying variables, and for generating known values to pass
69 to other programs.
70
71 ## Moving around the file system
72
73 Let's learn how to move around the file system using command line
74 programs. This is really easy to do using a GUI (just click on
75 things). Once you learn the basic commands, you'll see that it is
76 really easy to do in the shell too. 
77
78 First we have to know where we are. The program `pwd` (print working
79 directory) tells you where you are sitting in the directory tree. The
80 command `ls` will list the files in files in the current
81 directory. Directories are often called "folders" because of how they
82 are represented in GUIs. Directories are just listings of files. They
83 can contain other files or directories.
84
85 Whenever you start up a terminal, you will start in a special
86 directory called the *home* directory. Every user has their own home
87 directory where they have full access to do whatever they want. In
88 this case, the `pwd` command tells us that we are in the `/home/swc`
89 directory. This is the home directory for the `swc` user. That is our
90 user name. You can always find out your user name by entering the
91 command `whoami`. 
92
93 ## File Types
94
95 When you enter the `ls` command lists the contents of the current
96 directory. There are several items in the home directory, notice that
97 they are all colored blue. This tells us that all of these items are
98 directories as opposed to files.
99
100 Lets create an empty file using the `touch` command. Enter the
101 command:
102
103     touch testfile
104
105 Then list the contents of the directory again. You should see that a
106 new entry, called `testfile`, exists. It is colored white meaning that
107 it is a file, as opposed to a directory. The `touch` command just
108 creates an empty file. 
109
110 Some terminals will not color the directory entries in this very
111 convenient way. In those terminals, use `ls -F` instead of `ls`. The
112 `-F` argument modifies the results so that a slash is placed at the
113 end of directories. If the file is *executable* meaning that it can be
114 run like a program, then a star will be placed at the end of of the
115 file name.
116
117 You can also use the command `ls -l` to see whether items in a
118 directory are files or directories. `ls -l` gives a lot more
119 information too, such as the size of the file and information about
120 the owner. If the entry is a directory, then the first letter will be
121 a "d". The fifth column shows you the size of the entries in
122 bytes. Notice that `testfile` has a size of zero.
123
124 Now, let's get rid of `testfile`. To remove a file, just enter the
125 command:
126
127     rm testfile
128
129 The `rm` command can be used to remove files. If you enter `ls` again,
130 you will see that `testfile` is gone.
131
132
133 ## Changing Directories
134
135 Now, let's move to a different directory. The command `cd` (change
136 directory) is used to move around. Let's move into the `boot-camps`
137 directory. Enter the following command:
138
139     cd boot-camps
140
141 Now use the `ls` command to see what is inside this directory. You
142 will see that there is an entry which is green. This means that this
143 is an executable. If you use `ls -F` you will see that this file ends
144 with a star.
145
146 This directory contains all of the material for this boot camp. Now
147 move to the directory containing the data for the shell tutorial:
148
149     cd shell
150
151 If you enter the `cd` command by itself, you will return to the home
152 directory. Try this, and then navigate back to the `shell`
153 directory.
154
155 ## Arguments
156
157 Most programs take additional arguments that control their exact
158 behavior. For example, `-F` and `-l` are arguments to `ls`.  The `ls`
159 program, like many programs, take a lot of arguments. But how do we
160 know what the options are to particular commands?
161
162 Most commonly used shell programs have a manual. You can access the
163 manual using the `man` program. Try entering:
164
165     man ls
166
167 This will open the manual page for `ls`. Use the space key to go
168 forward and b to go backwards. When you are done reading, just hit `q`
169 to quit.
170
171 Programs that are run from the shell can get extremely complicated. To
172 see an example, open up the manual page for the `find` program,
173 which we will use later this session. No one can possibly learn all of
174 these arguments, of course. So you will probably find yourself
175 referring back to the manual page frequently.
176
177 * * * *
178 **Short Exercise**
179
180 1. Use the manual page for `ls` to guess what you would expect from
181 using the arguments `-l`, '-t', '-r' at the same time.
182 2. Try the following and see if you can figure out what they do, either by examining the results or consulting the manual page.
183    * `ls -lS` (equivalent to `ls -l -S`)
184    * `ls -lt` (equivalent to `ls -l -t`)
185    * `ls -1`  (that's the number one, not a letter 'ell')
186
187 * * * *
188
189
190 ## Examining the contents of other directories
191
192 By default, the `ls` commands lists the contents of the working
193 directory (i.e. the directory you are in). You can always find the
194 directory you are in using the `pwd` command. However, you can also
195 give `ls` the names of other directories to view. Navigate to the
196 home directory if you are not already there. Then enter the
197 command:
198
199     ls boot-camps
200
201 This will list the contents of the `boot-camps` directory without
202 you having to navigate there. Now enter:
203
204     ls boot-camps/shell
205
206 This prints the contents of `shell`. The `cd` command works in a
207 similar way. Try entering:
208
209     cd boot-camps/shell
210
211 and you will jump directly to `shell` without having to go through
212 the intermediate directory.
213
214 ## Full vs. Relative Paths
215
216 The `cd` command takes an argument which is the directory
217 name. Directories can be specified using either a *relative* path a
218 full *path*. The directories on the computer are arranged into a
219 hierarchy. The full path tells you where a directory is in that
220 hierarchy. Navigate to the home directory. Now, enter the `pwd`
221 command and you should see:
222
223     /home/swc
224
225 which is the full name of your home directory. This tells you that you
226 are in a directory called `swc`, which sits inside a directory called
227 `home` which sits inside the very top directory in the hierarchy. The
228 very top of the hierarchy is a directory called `/` which is usually
229 referred to as the *root directory*. So, to summarize: `swc` is a
230 directory in `home` which is a directory in `/`.
231
232 Now enter the following command:
233
234     cd /home/swc/boot-camps/shell
235
236 This jumps to `shell`. Now go back to the home directory. We saw
237 earlier that the command:
238
239     cd boot-camps/shell
240
241 had the same effect - it took us to the `shell` directory. But,
242 instead of specifying the full path
243 (`/home/swc/boot-camps/shell`), we specified a *relative path*. In
244 other words, we specified the path relative to our current
245 directory. A full path always starts with a `/`. A relative path does
246 not. You can usually use either a full path or a relative path
247 depending on what is most convenient. If we are in the home directory,
248 it is more convenient to just enter the relative path since it
249 involves less typing.
250
251 Over time, it will become easier for you to keep a mental note of the
252 structure of the directories that you are using hand how to quickly
253 navigate amongst them.
254
255 * * * *
256 **Short Exercise**
257
258 Now, list the contents of the /bin directory. Do you see anything
259 familiar in there?
260
261 * * * * 
262
263 ## Saving time with shortcuts, wild cards, and tab completion
264
265 ### Shortcuts
266
267 There are some shortcuts which you should know about. Dealing with the
268 home directory is very common. So, in the shell the tilde character,
269 `~`, is a shortcut for your home directory. Navigate to the `shell`
270 directory, then enter the command:
271
272     ls ~
273
274 This prints the contents of your home directory, without you having to
275 type the full path. The shortcut `..` always refers to the directory
276 above your current directory. Thus: 
277
278     ls ..
279
280 prints the contents of the `/home/swc/boot-camps`. You can chain
281 these together, so:
282
283     ls ../../
284
285 prints the contents of `/home/swc` which is your home
286 directory. Finally, the special directory `.` always refers to your
287 current directory. So, `ls`, `ls .`, and `ls ././././.` all do the
288 same thing, they print the contents of the current directory. This may
289 seem like a useless shortcut right now, but we'll see when it is
290 needed in a little while.
291
292 To summarize, while you are in the `shell` directory, the commands
293 `ls ~`, `ls ~/.`, `ls ../../`, and `ls /home/swc` all do exactly the
294 same thing. These shortcuts are not necessary, they are provided for
295 your convenience.
296
297 ### Our data set: Cochlear Implants
298
299 A cochlear implant is a small electronic device that is surgically
300 implanted in the inner ear to give deaf people a sense of
301 hearing. More than a quarter of a million people have them, but there
302 is still no widely-accepted benchmark to measure their effectiveness.
303 In order to establish a baseline for such a benchmark, our supervisor
304 got teenagers with CIs to listen to audio files on their computer and
305 report:
306
307 1.  the quietest sound they could hear
308 2.  the lowest and highest tones they could hear
309 3.  the narrowest range of frequencies they could discriminate
310
311 To participate, subjects attended our laboratory and one of our lab
312 techs played an audio sample, and recorded their data - when they
313 first heard the sound, or first heard a difference in the sound.  Each
314 set of test results were written out to a text file, one set per file.
315 Each participant has a unique subject ID, and a made-up subject name.
316 Each experiment has a unique experiment ID. The experiment has
317 collected 351 files so far.
318
319 The data is a bit of a mess! There are inconsistent file names, there
320 are extraneous "NOTES" files that we'd like to get rid of, and the
321 data is spread across many directories. We are going to use shell
322 commands to get this data into shape. By the end we would like to:
323
324 1.  Put all of the data into one directory called "alldata"
325
326 2.  Have all of the data files in there, and ensure that every file
327     has a ".txt" extension
328
329 3.  Get rid of the extraneous "NOTES" files
330
331 If we can get through this example in the available time, we will move
332 onto more advanced shell topics...
333
334 ### Wild cards
335
336 Navigate to the `~/boot-camps/shell/data/THOMAS` directory. This
337 directory contains our hearing test data for THOMAS. If we type `ls`,
338 we will see that there are a bunch of files which are just four digit
339 numbers. By default, `ls` lists all of the files in a given
340 directory. The `*` character is a shortcut for "everything". Thus, if
341 you enter `ls *`, you will see all of the contents of a given
342 directory. Now try this command:
343
344     ls *1
345
346 This lists every file that ends with a `1`. This command:
347
348     ls /usr/bin/*.sh
349
350 Lists every file in `/usr/bin` that ends in the characters `.sh`. And
351 this command:
352
353     ls *4*1
354
355 lists every file in the current directory which contains the number
356 `4`, and ends with the number `1`. There are four such files: `0241`,
357 `0341`, `0431`, and `0481`. 
358
359 So how does this actually work? Well...when the shell (bash) sees a
360 word that contains the `*` character, it automatically looks for files
361 that match the given pattern. In this case, it identified four such
362 files. Then, it replaced the `*4*1` with the list of files, separated
363 by spaces. In other words, the two commands:
364
365     ls *4*1
366     ls 0241 0341 0431 0481
367
368 are exactly identical. The `ls` command cannot tell the difference
369 between these two things.
370
371 * * * *
372 **Short Exercise**
373
374 Do each of the following using a single `ls` command without
375 navigating to a different directory.
376
377 1.  List all of the files in `/bin` that contain the letter `a`
378 2.  List all of the files in `/bin` that contain the letter `a` or the letter `b`
379 3.  List all of the files in `/bin` that contain the letter `a` AND the letter `b`
380
381 * * * *
382
383 ### Tab Completion
384
385 Navigate to the home directory. Typing out directory names can waste a
386 lot of time. When you start typing out the name of a directory, then
387 hit the tab key, the shell will try to fill in the rest of the
388 directory name. For example, enter:
389
390     cd b<tab>
391
392 The shell will fill in the rest of the directory name for
393 `boot-camps`. Now enter:
394
395     ls s<tab><tab>
396
397 When you hit the first tab, nothing happens. The reason is that there
398 are multiple directories in the home directory which start with
399 `s`. Thus, the shell does not know which one to fill in. When you hit
400 tab again, the shell will list the possible choices. 
401
402 Tab completion can also fill in the names of programs. For example,
403 enter `e<tab><tab>`. You will see the name of every program that
404 starts with an `e`. One of those is `echo`. If you enter `ec<tab>` you
405 will see that tab completion works.
406
407 ## Command History
408
409 You can easily access previous commands.  Hit the up arrow.  
410 Hit it again.  You can step backwards through your command history. 
411 The down arrow takes your forwards in the command history.  
412
413 ^-C will cancel the command you are writing, and give you a fresh prompt.
414
415 ^-R will do a reverse-search through your command history.  This
416 is very useful.
417
418 ## Which program?
419
420 Commands like `ls`, `rm`, `echo`, and `cd` are just ordinary programs
421 on the computer. A program is just a file that you can *execute*. The
422 program `which` tells you the location of a particular program. For
423 example:
424
425     which ls
426
427 Will return "/bin/ls". Thus, we can see that `ls` is a program that
428 sits inside of the `/bin` directory. Now enter:
429
430     which find
431
432 You will see that `find` is a program that sits inside of the
433 `/usr/bin` directory.
434
435 So ... when we enter a program name, like `ls`, and hit enter, how
436 does the shell know where to look for that program? How does it know
437 to run `/bin/ls` when we enter `ls`. The answer is that when we enter
438 a program name and hit enter, there are a few standard places that the
439 shell automatically looks. If it can't find the program in any of
440 those places, it will print an error saying "command not found". Enter
441 the command:
442
443     echo $PATH
444
445 This will print out the value of the `PATH` environment variable. More
446 on environment variables later. Notice that a list of directories,
447 separated by colon characters, is listed. These are the places the
448 shell looks for programs to run. If your program is not in this list,
449 then an error is printed. The shell ONLY checks in the places listed
450 in the `PATH` environment variable. 
451
452 Navigate to the `shell` directory and list the contents. You will
453 notice that there is a program (executable file) called `hello` in
454 this directory. Now, try to run the program by entering:
455
456     hello
457
458 You should get an error saying that hello cannot be found. That is
459 because the directory `/home/swc/boot-camps/shell` is not in the
460 `PATH`. You can run the `hello` program by entering:
461
462     ./hello
463
464 Remember that `.` is a shortcut for the current working
465 directory. This tells the shell to run the `hello` program which is
466 located right here. So, you can run any program by entering the path
467 to that program. You can run `hello` equally well by specifying:
468
469     /home/swc/boot-camps/shell/hello
470
471 Or by entering:
472
473     ../shell/hello
474
475 When there are no `/` characters, the shell assumes you want to look
476 in one of the default places for the program.
477
478
479 ## Examining Files
480
481 We now know how to switch directories, run programs, and look at the
482 contents of directories, but how do we look at the contents of files?
483
484 The easiest way to examine a file is to just print out all of the
485 contents using the program `cat`. Enter the following command:
486
487     cat ex_data.txt
488
489 This prints out the contents of the `ex_data.txt` file. If you enter:
490
491     cat ex_data.txt ex_data.txt
492
493 It will print out the contents of `ex_data.txt` twice. `cat` just
494 takes a list of file names and writes them out one after another (this
495 is where the name comes from, `cat` is short for concatenate). 
496
497 * * * *
498 **Short Exercises**
499
500 1.  Print out the contents of the `~/boot-camps/shell/dictionary.txt`
501     file. What does this file contain?
502
503 2.  Without changing directories, (you should still be in `shell`),
504     use one short command to print the contents of all of the files in
505     the `/home/swc/boot-camps/shell/data/THOMAS` directory.
506
507 * * * *
508
509 `cat` is a terrific program, but when the file is really big, it can
510 be annoying to use. The program, `less`, is useful for this
511 case. Enter the following command:
512
513     less ~/boot-camps/shell/dictionary.txt
514
515 `less` opens the file, and lets you navigate through it. The commands
516 are identical to the `man` program. 
517
518 | "space" | to go forward |
519 |  "b"    | to go backwarsd |
520 |  "g"    | to go to the beginning |
521 |  "G"    | to go to the end |
522 |  "q"    | to quit |
523
524 `less` also gives you a way of searching through files. Just hit the
525 "/" key to begin a search. Enter the name of the word you would like
526 to search for and hit enter. It will jump to the next location where
527 that word is found. Try searching the `dictionary.txt` file for the
528 word "cat". If you hit "/" then "enter", `less` will just repeat
529 the previous search. `less` searches from the current location and
530 works its way forward. If you are at the end of the file and search
531 for the word "cat", `less` will not find it. You need to go to the
532 beginning of the file and search.
533
534 Remember, the `man` program actually uses `less` internally and
535 therefore uses the same commands, so you can search documentation
536 using "/" as well!
537
538 * * * *
539 **Short Exercise**
540
541 Use the commands we've learned so far to figure out how to search
542 in reverse while using `less`.
543
544 * * * * 
545
546
547 ## Redirection
548
549 Let's turn to the experimental data from the hearing tests that we
550 began with. This data is located in the `~/boot-camps/shell/data`
551 directory. Each subdirectory corresponds to a particular participant
552 in the study. Navigate to the `Bert` subdirectory in `data`.  There
553 are a bunch of text files which contain experimental data
554 results. Lets print them all:
555
556     cat au*
557
558 Now enter the following command:
559
560     cat au* > ../all_data
561
562 This tells the shell to take the output from the `cat au*` command and
563 dump it into a new file called `../all_data`. To verify that this
564 worked, examine the `all_data` file. If `all_data` had already
565 existed, we would overwritten it. So the `>` character tells the shell
566 to take the output from what ever is on the left and dump it into the
567 file on the right. The `>>` characters do almost the same thing,
568 except that they will append the output to the file if it already
569 exists.
570
571 * * * *
572 **Short Exercise**
573
574 Use `>>`, to append the contents of all of the files whose names
575 contain the number 4 in the directory:
576
577     /home/swc/boot-camps/shell/data/gerdal
578
579 to the existing `all_data` file. Thus, when you are done `all_data`
580 should contain all of the experiment data from Bert and any
581 experimental data file from gerdal with filenames that contain the
582 number 4.
583
584 * * * *
585
586
587 ## Creating, moving, copying, and removing
588
589 We've created a file called `all_data` using the redirection operator
590 `>`. This file is critical - it's our analysis results - so we want to
591 make copies so that the data is backed up.
592 Lets copy the file using the `cp` command. The `cp`
593 command backs up the file. Navigate to the `data` directory and enter:
594
595     cp all_data all_data_backup
596
597 Now `all_data_backup` has been created as a copy of `all_data`. We can
598 move files around using the command `mv`. Enter this command:
599
600     mv all_data_backup /tmp/
601
602 This moves `all_data_backup` into the directory `/tmp`. The directory
603 `/tmp` is a special directory that all users can write to. It is a
604 temporary place for storing files. Data stored in `/tmp` is
605 automatically deleted when the computer shuts down.
606
607 The `mv` command is also how you rename files. Since this file is so
608 important, let's rename it:
609
610     mv all_data all_data_IMPORTANT
611
612 Now the file name has been changed to all_data_IMPORTANT. Let's delete
613 the backup file now:
614
615     rm /tmp/all_data_backup
616
617 The `mkdir` command is used to make a directory. Just enter `mkdir`
618 followed by a space, then the directory name. 
619
620 * * * *
621 **Short Exercise**
622
623 Do the following:
624
625 1.  Rename the `all_data_IMPORTANT` file to `all_data`.
626 2.  Create a directory in the `data` directory called `foo`
627 3.  Then, copy the `all_data` file into `foo`
628
629 * * * *
630
631 By default, `rm`, will NOT delete directories. You can tell `rm` to
632 delete a directory using the `-r` option. Enter the following command:
633
634     rm -r foo
635
636
637 ## Count the words
638
639 The `wc` program (word count) counts the number of lines, words, and
640 characters in one or more files. Make sure you are in the `data`
641 directory, then enter the following command:
642
643     wc Bert/* gerdal/*4*
644
645 For each of the files indicated, `wc` has printed a line with three
646 numbers. The first is the number of lines in that file. The second is
647 the number of words. Finally, the total number of characters is
648 indicated. The final line contains this information summed over all of
649 the files. Thus, there were 10445 characters in total. 
650
651 Remember that the `Bert/*` and `gerdal/*4*` files were merged
652 into the `all_data` file. So, we should see that `all_data` contains
653 the same number of characters:
654
655     wc all_data
656
657 Every character in the file takes up one byte of disk space. Thus, the
658 size of the file in bytes should also be 10445. Let's confirm this:
659
660     ls -l all_data
661
662 Remember that `ls -l` prints out detailed information about a file and
663 that the fifth column is the size of the file in bytes.
664
665 * * * *
666 **Short Exercise**
667
668 Figure out how to get `wc` to print the length of the longest line in
669 `all_data`.
670
671 * * * *
672
673 ## The awesome power of the Pipe
674
675 Suppose I wanted to only see the total number of character, words, and
676 lines across the files `Bert/*` and `gerdal/*4*`. I don't want to
677 see the individual counts, just the total. Of course, I could just do:
678
679     wc all_data
680
681 Since this file is a concatenation of the smaller files. Sure, this
682 works, but I had to create the `all_data` file to do this. Thus, I
683 have wasted a precious 7062 bytes of hard disk space. We can do this
684 *without* creating a temporary file, but first I have to show you two
685 more commands: `head` and `tail`. These commands print the first few,
686 or last few, lines of a file, respectively. Try them out on
687 `all_data`:
688
689     head all_data
690     tail all_data
691
692 The `-n` option to either of these commands can be used to print the
693 first or last `n` lines of a file. To print the first/last line of the
694 file use:
695
696     head -n 1 all_data
697     tail -n 1 all_data
698
699 Let's turn back to the problem of printing only the total number of
700 lines in a set of files without creating any temporary files. To do
701 this, we want to tell the shell to take the output of the `wc Bert/*
702 gerdal/*4*` and send it into the `tail -n 1` command. The `|`
703 character (called pipe) is used for this purpose. Enter the following
704 command:
705
706     wc Bert/* gerdal/Data0559 | tail -n 1
707
708 This will print only the total number of lines, characters, and words
709 across all of these files. What is happening here? Well, `tail`, like
710 many command line programs will read from the *standard input* when it
711 is not given any files to operate on. In this case, it will just sit
712 there waiting for input. That input can come from the user's keyboard
713 *or from another program*. Try this:
714
715     tail -n 2
716
717 Notice that your cursor just sits there blinking. Tail is waiting for
718 data to come in. Now type:
719
720     French
721     fries
722     are
723     good
724
725 then CONTROL+d. You should is the lines:
726
727     are
728     good
729
730 printed back at you. The CONTROL+d keyboard shortcut inserts an
731 *end-of-file* character. It is sort of the standard way of telling the
732 program "I'm done entering data". The `|` character is replaces the
733 data from the keyboard with data from another command. You can string
734 all sorts of commands together using the pipe. 
735
736 The philosophy behind these command line programs is that none of them
737 really do anything all that impressive. BUT when you start chaining
738 them together, you can do some really powerful things really
739 efficiently. If you want to be proficient at using the shell, you must
740 learn to become proficient with the pipe and redirection operators:
741 `|`, `>`, `>>`.
742
743
744 ### A sorting example
745
746 Let's create a file with some words to sort for the next example. We
747 want to create a file which contains the following names:
748
749     Bob
750     Alice
751     Diane
752     Charles
753
754 To do this, we need a program which allows us to create text
755 files. There are many such programs, the easiest one which is
756 installed on almost all systems is called `nano`. Navigate to `/tmp`
757 and enter the following command:
758
759     nano toBeSorted
760
761 Now enter the four names as shown above. When you are done, press
762 CONTROL+O to write out the file. Press enter to use the file name
763 `toBeSorted`. Then press CONTROL+x to exit `nano`.
764
765 When you are back to the command line, enter the command:
766
767     sort toBeSorted
768
769 Notice that the names are now printed in alphabetical order.
770
771 * * * *
772 **Short Exercise**
773
774 Use the `echo` command and the append operator, `>>`, to append your
775 name to the file, then sort it and make a new file called Sorted.
776
777 * * * *
778
779 Let's navigate back to `~/boot-camps/shell/data`. Enter the following command:
780
781     wc Bert/* | sort -k 3 -n
782
783 We are already familiar with what the first of these two commands
784 does: it creates a list containing the number of characters, words,
785 and lines in each file in the `Bert` directory. This list is then
786 piped into the `sort` command, so that it can be sorted. Notice there
787 are two options given to sort:
788
789 1.  `-k 3`: Sort based on the third column
790 2.  `-n`: Sort in numerical order as opposed to alphabetical order
791
792 Notice that the files are sorted by the number of characters.
793
794 * * * *
795 **Short Exercise**
796
797 1. Use the `man` command to find out how to sort the output from `wc` in
798 reverse order.
799
800 2. Combine the `wc`, `sort`, `head` and `tail` commands so that only the
801 `wc` information for the largest file is listed
802
803 Hint: To print the smallest file, use:
804
805     wc Bert/* | sort -k 3 -n | head -n 1
806
807 * * * * 
808
809 Printing the smallest file seems pretty useful. We don't want to type
810 out that long command often. Let's create a simple script, a simple
811 program, to run this command. The program will look at all of the
812 files in the current directory and print the information about the
813 smallest one. Let's call the script `smallest`. We'll use `nano` to
814 create this file. Navigate to the `data` directory, then:
815
816     nano smallest
817
818 Then enter the following text:
819
820     #!/bin/bash
821     wc * | sort -k 3 -n | head -n 1
822
823 Now, `cd` into the `Bert` directory and enter the command
824 `../smallest`. Notice that it says permission denied. This happens
825 because we haven't told the shell that this is an executable
826 file. If you do `ls -l ../smallest`, it will show you the permissions on 
827 the left of the listing.
828
829 Enter the following commands:
830
831     chmod a+x ../smallest
832     ../smallest
833
834 The `chmod` command is used to modify the permissions of a file. This
835 particular command modifies the file `../smallest` by giving all users
836 (notice the `a`) permission to execute (notice the `x`) the file. If
837 you enter:
838
839     ls -l ../smallest
840
841 You will see that the file name is green and the permissions have changed. 
842 Congratulations, you just created your first shell script!
843
844 # Searching files
845
846 You can search the contents of a file using the command `grep`. The
847 `grep` program is very powerful and useful especially when combined
848 with other commands by using the pipe. Navigate to the `Bert`
849 directory. Every data file in this directory has a line which says
850 "Range". The range represents the smallest frequency range that can be
851 discriminated. Lets list all of the ranges from the tests that Bert
852 conducted:
853
854     grep Range *
855
856 * * * * 
857 **Short Exercise**
858
859 Create an executable script called `smallestrange` in the `data`
860 directory, that is similar to the `smallest` script, but prints the
861 file containing the file with the smallest Range. Use the commands
862 `grep`, `sort`, and `tail` to do this.
863
864 * * * * 
865
866
867 # Finding files
868
869 The `find` program can be used to find files based on arbitrary
870 criteria. Navigate to the `data` directory and enter the following
871 command:
872
873     find . -print
874
875 This prints the name of every file or directory, recursively, starting
876 from the current directory. Let's exclude all of the directories:
877
878     find . -type f -print
879
880 This tells `find` to locate only files. Now try these commands:
881
882     find . -type f -name "*1*"
883     find . -type f -name "*1*" -or -name "*2*" -print
884     find . -type f -name "*1*" -and -name "*2*" -print
885
886 The `find` command can acquire a list of files and perform some
887 operation on each file. Try this command out:
888
889     find . -type f -exec grep Volume {} \;
890
891 This command finds every file starting from `.`. Then it searches each
892 file for a line which contains the word "Volume". The `{}` refers to
893 the name of each file. The trailing `\;` is used to terminate the
894 command.  This command is slow, because it is calling a new instance
895 of `grep` for each item the `find` returns.
896
897 A faster way to do this is to use the `xargs` command:
898
899     find . -type f -print | xargs grep Volume
900
901 `find` generates a list of all the files we are interested in, 
902 then we pipe them to `xargs`.  `xargs` takes the items given to it 
903 and passes them as arguments to `grep`.  `xargs` generally only creates
904 a single instance of `grep` (or whatever program it is running).
905
906 * * * * 
907 **Short Exercise**
908
909 Navigate to the `data` directory. Use one `find` command to perform each
910 of the operations listed below (except number 2, which does not
911 require a `find` command):
912
913 1.  Find any file whose name is "NOTES" within `data` and delete it 
914
915 2.  Create a new directory called `cleaneddata`
916
917 3.  Move all of the files within `data` to the `cleaneddata` directory
918
919 4.  Rename all of the files to ensure that they end in `.txt` (note:
920     it is ok for the file name to end in `.txt.txt`
921
922 Hint: If you make a mistake and need to start over just do the
923 following:
924
925 1.  Navigate to the `shell` directory
926
927 2.  Delete the `data` directory
928
929 3.  Enter the command: `git checkout -- data` You should see that the
930     data directory has reappeared in its original state
931
932 **BONUS**
933
934 Redo exercise 4, except rename only the files which do not already end
935 in `.txt`. You will have to use the `man` command to figure out how to
936 search for files which do not match a certain name. 
937
938 * * * * 
939
940
941
942 ## Bonus:
943
944 **backtick, xargs**: Example find all files with certain text
945
946 **alias** -> rm -i
947
948 **variables** -> use a path example
949
950 **.bashrc**
951
952 **du**
953
954 **ln**
955
956 **ssh and scp**
957
958 **Regular Expressions**
959
960 **Permissions**
961
962 **Chaining commands together**