Using the Shell

The “shell” is the command interpreter: the program that listens to your terminal and understands the words you type as commands and arguments. The shell we use here is called the C shell (csh, tcsh, etc) because its command syntax is similar to the C programming language. Not only does the shell execute your commands, but it also has nice features such as filename completion, command aliasing, history substitution, and job control which will make using the system easier.  A very popular shell in recent years is bash, which is the default on macOS, Cygwin, and many Linux distributions.  They may look slightly different but they are similar enough that most of the commands here work the same way.

Using the shell is easy. For instance, if you type “date” followed by a Return, the shell will print out the current date and time on your terminal screen. The “ls” command will print out a list of your files on your terminal screen. Both of these commands send their output to the standard output device (or “stdout”) which is usually the terminal. The standard input device (“stdin”) is the terminal’s keyboard.

2.1 Start-up

When you first log in, the shell looks for the files ‘.login’ and ‘.cshrc’ (for csh) or ‘.bash_profile’ (for bash) and executes the commands in those files. These files make it possible for you to tailor your working environment to your specifications and to ensure that environment is always the same.

Why two files? The commands in ‘.login’ are executed only when you log into the system. It sets up your terminal type and performs other one-time tasks. The commands in ‘.cshrc’ are executed every time a new shell (csh) is started up, like when you fork out of a program back to the shell. The commands in ‘.bash_profile’ are executed on startup of bash.

When you log out (by typing “logout”), the shell will run the commands in your ‘.logout’ file.

2.2 Filename Completion

When you have the command “set filec” in your ‘.cshrc’ file, the shell can complete the partially typed name of a file or user name. When you type the first few unique characters of a file name and then press the Esc key, the system will complete the filename for you. If it is not clear which file you want (the first few characters you typed are not unique to one filename), the terminal will beep at you. In bash, you can do the same by pressing the tab key without set filec.

In csh, if the partial filename is followed by CTRL-D , the shell will list all the matching filenames. It will then prompt you again, retyping the command line as you have typed it so far. In bash, you can type tab twice to achieve the same effect.

2.3 History Substitution

History substitution allows you to use words from previous command lines in the command line you are currently typing. This makes it easier to correct simple errors in complicated command lines. To do this, the shell has a built-in mechanism that keeps track of some number of the commands you have typed. For example, the command “set history=10” in your ‘.cshrc’ file will tell the shell to remember the last 10 commands you have typed:

   % history
       1  6:33 ls
       2 6:33 date
       3 6:34
   % _

This shows that I have given 3 commands: “ls”, “date”, and “history”. The 6:33, 6:34 etc are the times those commands were typed.

A history substitution command begins with an exclamation point or “bang sign” (!). The command “!!” will repeat your previous command. If you give the “date” command and then “!!”, the “date” program will run again:

   % date
   Mon Sep 16 14:21:01 PDT 2013
   % !!
   date
   Mon Sep 16 14:21:04 PDT 2013
   %

Here are some ways you can use history substitutions:
!! re-run the previous command
!n re-run command on line number n (from the history listing)
!string re-run last command beginning with string
ˆword1ˆword2 In previous command, substitute word2 for word1.

2.4 Aliases

The term “alias” means another name for something. Another feature of the C Shell allows you to give new, short names for long, frequently used commands with the “alias” command.

In csh, it is

   alias newname ’long command string’

In bash, it is

   alias newname=’long command string’

For example, if you frequently use the “find” command to look through all your directories to find files named ‘core’, you could make the following alias:

(csh)

    % alias find_core ’find .  -name core -print’

(bash)

    % alias find_core=’find . -name core -print’

Now you have a new shorter command (“find_core”) that you can use to find ‘core’ files.

You can put the “alias” command in your ‘.cshrc’ or .bashrc (or .bash_profile) file so that you can use them every time you log in. Aliases can be removed with the “unalias” command.

2.5 Using Files Instead of the Terminal

When you run a program, the program usually produces some output which appears on your terminal screen. If you wish, you can redirect the output into a file. For example, the “who” command will produce output like this:

   % who
   operator console Sep  3 05:59
   eauu016  ttyp4   Sep  4 14:07 (csi-ts3.nts.uci.)
   eaacct   ttype   Sep  3 15:25 (csi-ts3.nts.uci.)
   nest     ttypf   Sep  4 08:18 (ghostbusters.nts)
   eapu163  ttyq2   Sep  4 10:47 (csi-ts3.nts.uci.)
   operator ttyq3   Sep  3 15:57 (csi-ts3.nts.uci.)

You can redirect the output from “who” into a file by typing:

    % who > who_file

This command will create a new file called ‘who_file’ that contains the output from the “who” command. If you already had a file called ‘who_file’, its contents would be replaced by the output from “who”. If you wish to append to an existing file, you can use two “greater than” signs:

   % who >> who_file

2.6 Pipes

Pipes connect the standard output of one program to the standard input of another. To do this, just type the two commands with a “|” (vertical bar) between them.

Let’s say that you want to see if your friend, John Smith, is logged in, but you don’t want to look through all the output from “who”. You can take the output from “who” and pipe it through “grep” like this:

   % who | grep jsmith
   jsmith ttyqo Jan 29 13:12

[“grep” is one in a family of programs that search through a file (or other input) to find a matching pattern. Type “man grep” for more details.]

If he is not, you won’t get any output.

Quite often it is useful to pipe the output from a different program to the “more” program. This will show you the output a page at a time.

2.7 Environment Variables

The shell lets you define a variable and assign a value to it. Many programs take advantage of this ability. For example, many programs that start up a text editor (such as “vi” or “emacs”) look at the variable EDITOR to see which editor you wish to use. These variables are usually set in the ‘.login’ or ‘.cshrc’ (csh) or ‘.bashrc’ or .bash_profile’ (bash) files.

Here are some different ways of setting environment variables: (these are for csh, which is the default on the Sun instructional account)

   setenv EDITOR emacs
   setenv PAGER /usr/ucb/more

If you use bash (the default shell in Cygwin, recent versions of macOS, and Linux), then you need to adjust the syntax slightly:

   export EDITOR=emacs
   export PAGER=/usr/ucb/more

The shell also defines some variables for you such as HOME, which is your home directory, and PATH, which is the list of directories searched for executable files. The “man” pages for various programs will tell you which environment variables they use.

2.8 Filenames

The Unix filesystem looks like an upside down tree. There is one directory at the top called ‘/’ (slash) or the “root” directory. All the other files in the filesystem are “below” this directory in many layers of subdirectories. If I type “pwd” (Print Working Directory) I will find out the name of my current directory:

    % pwd /users/physics/jsmith
    %_

This shows that my current directory is called ‘jsmith’ and it is “under” the directories ‘/users’ and ‘/physics’. I can list the files in my current directory by typing “ls” and I can see what files are in a different directory by typing “ls” followed by a path. For example, what files are kept in ’/usr/local’?

 

% ls /usr/local
IDEpipesh*     fanno@         nbbc*           rmf*
Pnews*         fc*            netcon*         rmm*
Rnmail*        finger*        newsetup*       rmt*
ali*           folder*        newsgroups*     rn*
anno*          folders*       next*           rprompt*
ansitar*       forw*          nmsh*           rrn@
apropos@       fstype*        nn*             rtar*
% _
 

[The directory name ‘/usr/local’ is an “absolute” or “rooted” pathname because it starts with ‘/’ (the root directory).]

There are certain shorthand ways of referring to files or groups of files without typing the full filename(s). The special characters that allow this are sometimes called “wildcard” characters. The most popular one is “*” which will match any or all characters. For example, “ls f*” will list all files in the current directory that begin with f, or “ls a*b” will list all files that begin with a and end with b.

* matches any characters
? matches any one character
[abc] matches characters a or b or c

 

2.9 Job Control

Unix allows you to suspend a program you are running and then go back to it later on. This is called “job control”. When you are using a program interactively, it is said to be in the “foreground”; once it is stopped (with CTRL-Z ) it is in the “background”. At this point you can put the job back into the foreground by typing “fg”, or tell it to continue to run in the background with “bg”. The shell gives a number to each job that is running in the background or that has been stopped. To see the list of current jobs, type “jobs”. Each job will be listed, preceded by its number. The job most recently stopped is referred to as the current job and will have a + sign in front of it. You can kill a job by typing:

    % kill %n 

where n is the number of the job. A job left running in the background will stop when it needs input from the terminal.

2.10 Useful Commands

alias name command Assign command to alias name. If command is omitted, the alias name is shown along with its current definition.
bg [%n] Run the current (or specified) job in the background.
cc file.c  C language compiler. Translates C input files ‘file.c’ into a machine executable program (‘a.out’)
cd [dir] Change your working directory to ‘dir’. If dir is omitted, change to your home directory.
cp oldfile newfile Make a copy of ‘oldfile’ and call it ‘newfile’.
exit Quit the current shell.
f77 file.f Fortran language compiler. Translates Fortran input files ‘file.f ’ into a machine executable program (‘a.out’).
fg [%n] Bring current job or specified job (%n) into the foreground.
fgrep string filename  Search for pattern string in file ‘filename’.
history [n] Display the history list. If is given, display only the most recent items.
jobs List the jobs under job control.
kill n Terminate process n, where is determined with the “ps” command. If the job is running in the background, you can use the “jobs” command to find out the job number. In this situation the command would take the form: “kill %n”. Terminate your login shell. 
logout Runs the commands in the file ‘.logout’.
lpr filename ls Sends file ‘filename’ to the lineprinter on the third floor of the CS building.
ls List the files in your current directory. “ls -l” will list the files in “long” format showing size, modification date, permissions, etc.
man command-name Gives information about the specified command-name. You can get more information about all the commands discussed in this section with the “man” command. Typing: “man -k keyword” will give you a short, one-line summary of all the commands dealing with that topic. If you wish to test this, try “man -k information
mkdir dirname Creates a directory with name ‘dirname’. The “rmdir” command is for removing empty directories
more filename Displays the file ‘filename’ on your terminal screen one screenful at a time. Press Return to see one more line and press Spacebar to see one more screen at a time.
mv oldname newname Changes the name of file ‘oldname’ to be ‘newname’. You can also move a file into another directory with: “mv file newdir”. This moves file ‘file’ into the directory ‘newdir’.
printenv Displays all the current environment variables and their values.
ps Shows information about processes which are running under your terminal. Use “ps x” to find out about all your processes. This command is useful if you need to find out the process ID of a process in order to “kill” it.
pwd Prints your current directory.
rm filename Deletes the file called ‘filename’. You might not be asked for confirmation, so be sure you want to remove the file before you type the command. To require confirmation, “rm -i filenames” will ask you to type “y” or “n” before deleting a file.
setenv [VAR [word]] When used alone (i.e. with no arguments) “setenv” will display all your environment variables and their values. With the VAR argument, the variable VAR will be given an empty (null) value. With both VAR and wordVAR will be given value “word”. [Environment variables are normally given upper case names.]
who See who is using the system. Try the “w” command for more info. 

 

Scholarly Lite is a free theme, contributed to the Drupal Community by More than Themes.