HowTos / Shell

Using the Linux Shell


(commands also available on Macs)

Topics covered: running executables, controlling processes, shell scripts, perl scripts, c/c++

running executables

  • How do I run an executable?

Type its complete path specification, either in absolute form

  #/home/dick/bin/answer
  #42 

or in relative form

  # pwd
  #/home/dick/bin
  #./answer
  #42 

If the program is in the current PATH, you can just type its name

  #answer
  #42 

For more information on the PATH variable, see the PATH section below.

  • How do I redirect the output of an executable to a file?

To redirect text output from the console to a file, use >

  #answer > output
  #cat output
  #42 

Actually, this redirects only STDOUT; STDERR, to which error messages are typically sent, will still be sent to the console. You can arrange to have STDERR redirected to its own file

  #answer 1>output 2>errors 

or to the same file as STDOUT

  #answer 1>output 2>& 

For more information on redirection, see the man page for your shell.

  • How do I run an executable in the background?

Type an amperstand (&) after the command. For example:

  #answer > output 2>&1 &
  #[1] 11333  

Don't forget to directy the output to a file you can read later. You will get a command prompt back immediately, and can use it to execute other commands as the program executes. The number which appears is the process id number (PID) of the process you have started.

  • How do I get an executable to continue running when I log out?

Preceed the command with "nohup" (for no hang-up)

  #nohup answer > output 2>&1 &
  #exit 

If the executable also produces graphical output, which you want to ignore, first disable graphical output

  #unset DISPLAY
  #nohup answer > output 2>&1 &
  #exit 

controling processes

  • How do I determine which processes are running?

Use the ps (process status) command with the aux option to list all running processes.

  #ps aux 
  USER       PID %CPU %MEM   VSZ  RSS TTY      STAT START   TIME COMMAND
  root         1  0.0  0.8  1376  548 ?        S    Sep01   0:08 init [3]
  root       753  0.0  1.8  2596 1176 ?        S    Sep01   0:06 /usr/sbin/sshd
  dick     11314  3.3  2.3  2612 1504 pts/0    S    21:11   0:00 bash
  dick     11333  0.5  6.1 10488 7908 pts/0    S    21:13   0:35 answer &
  dick     11350  0.0  1.1  2620  780 pts/0    R    22:15   0:00 ps aux 

(We have selected only a few lines from the output -- there are usually many more). For each running process, the owning user (USER), process id number (PID), percentage of processor cycles (MEM) currently used, total CPU time used (TIME), and several other useful pieces of information are displayed. To obtain information for specific processes, the grep command is very useful. For example, to obtain information on the answer process,

  #ps aux | grep answer
  dick     11333  0.5  6.1 10488 7908 pts/0    S    21:13   0:35 answer & 
  • How can I stop a running process?

You will need its PID, which you can determine using ps as explained above. You can send it a TERM signal,

  #ps aux | grep answer
  dick     11333  0.5  6.1 10488 7908 pts/0    S    21:13   0:35 answer &
  #kill 11333
  [1]+  Terminated              answer & 

which asks it to wrap up its business and terminate. If it has crashed, though, it may not respond to this signal. You can instead send it a KILL signal

  #kill -s SIGKILL 11333
  [1]+ Killed                   answer & 

or, using the equivilent but better-known short syntax,

  #kill -9 11333
  [1]+  Killed                  answer & 

which terminates it ("with extreme prejudice") directly. Note that you can only kill processes that belong to you.

  • How can I pause and later resume a running process?

To pause a running process, send it a STOP signal

  #kill -s SIGSTOP 11333
  [1]+  Stopped                 xemacs & 

To resume a stopped process, send it a CONT signal

  #kill -s SIGCONT 11333 

As you see, kill is not just a command for killing processes, but rather a command for sending them signals of all sorts.

path

  • How do I determine the PATH?
  #echo $PATH 
  • How do I change the PATH?

To change your path, edit this line in .bash_profile or .profile (assumes using bash, which is the default shell for our machines):

  PATH=$PATH:/usr/bin/X11:/usr/local/bin:/usr/sbin:/usr/bin:/bin 

This line should be somewhere below it:

  export PATH 

Make sure all paths are complete (start from the root directory), and there is a colon separating the paths. For example, to add caret to the path above:

 # Caret
 PATH=$PATH:/usr/bin/X11:/usr/local/bin:/usr/sbin:/usr/bin:/bin:/usr/local/caret/bin
 export PATH 
  • How do I find the path to an executable?

If the name of the executable is program:

  #which program 

This will give you the path, if the program is already on your path. If it is not on your path, you have to use the find command. If you know the program named program is in your home directory:

  #find ~/ -name program 

shell scripts

  • How do create a shell script?

The following is a simple hello world shell script.

  echo "Hello World!" 
  • How do I execute a shell script?

perl scripts

  • How do I create a simple perl script?

The following is a simple perl hello world program.

  #!/usr/bin/perl
  print("Hello World!\n"); 
  • How do I execute a perl script?

Save the hello world program above as hello. Hand it to the perl intrepreter.

  # '''perl hello'''
  Hello World! 

Alternatively, use chmod to make the file executable and let Unix hand it to the perl intrepreter by reading the #! line.

  #chmod u+x hello
  #./hello
  Hello World! 
  • How do I write more advanced perl scripts?

Perl (practical extraction and report language) was thrown together by Larry Wall in 1993 to expidite the parsing of data files to produce reports. It contains many commands to manipulate files, parse and format strings, and delegate tasks to other executables. Perl is often called the "duct tape of the internet" since it does such a bang-up job of easily tying together the functionalities of other applicatons.

c/c++

  • How do I write a simple c/c++ program?

The following is a simple c (and also c++) hello world program.

  #include<stdio.h>

  void main() {
    printf("Hello world!\n");
  } 
  • How do I compile and run a c/c++ program?

Save the hello world program above as hello.c and compile it usig the cnu c compiler gcc.

  #gcc hello.c -o hello
  #./hello
  Hello World! 

The option -o specifies the name of the executable to be produced, which traditionally has no extension.

  • How do I write more advanced c/c++ programs?

C is one of the oldest high-level languages. Designed for maximum simplicity (it contains less than 50 reserved words) so that a C compiler would be easy to create for any chip architecture, it is, as a side-effect, usually the language of choice for fast execution. Unix is written in C. Syntactically, C++ is a superset of C which adds object-oriented features, so C code is (usually) also valid C++.

  • How do I make my c/c++ program run even faster?

Tell gcc to optimize your code using a -O option.

  #gcc -O3 main.c -o main 

gcc offers three levels of optimization: -O1 (or -O), -O2, and -O3. Understanding the details of optimization requires familiarity with some of the details of compiler functionality, such as stack vs heap storage, function call overhead, and other whatnot. If you know these things, you can imagine what optimization does. For the rest of us, suffice to say that optimization decreases execution time at the expense of increasing compilation time.

  • How do I find the bottleneck in my code?

Use the gnu profiler gprof, which measures the time spent in each routine during execution.

  #gcc -pg main.c -o main
  #./main
  #gprof main gmon.out 

The gcc option -pg compiles in the hooks necessary for the gnu profiler to perform its measurements. When run, the executable produces the file gmon.out containing the profile informaton; gprof reads this file to produce a report containing the profile information. Very useful!

  • How do I link several objects into an executable?

You can use the -c option to have gcc compile files into an objects rather than executables. Object files need not contain a main routine, so you can collect libraries of routines which may be useful to multiple programs into object files. You can then use ld to link the required object files together into an executable, without having to recompile the libraries.

  #gcc -c program1.c program2.c library.c
  #ld program1.o library.o -o program1
  #ld program2.o library.o -o program2