Basic Linux Command Line Commands

Most of what we will do in this course can easily be done with a command- line window, sometimes called a shell window. The command-line window lets us type commands to run programs.

By default, command-line windows in Ubuntu uses the BASH command-line, and when you first launch it you will see a prompt something like this:

tjd@ubuntu-desktop:~/cmpt$

The key part of this prompt is the $. Everything before the $ is information about what computer you are using and what directory you are in. Everything after the $ is what you, the user, type.

The shell includes a complete programming language and dozens of commands. Here is a brief summary of basic commands you should know:

Sample Command Summary
pwd prints the present working directory
ls lists the files and folders in the current directory
cd a2 change to directory a2
rm old.cpp delete the file old.cpp
cp a1.cpp a1 copy file a1.cpp to the folder a1
man g++ display the manual page for the g++ command
less a1.cpp display contents of a file (paged)
cat a1.cpp display contents of a file (unpaged)

There are many tutorials and help pages available on the web for learning Linux command-line. For example, this tutorial list discusses many basic Linux commands, with helpful examples.

It is also common to manipulate files and folders interactively in the GUI. Just open the folder you want to change, and use the typical drag-and-drop actions to move, copy, rename, etc. files and folders.

File Redirection Using < and >

The ls command will list the files and folders in the current directory, e.g.:

$ ls
a1.h  a1_sol*  a1_sol.cpp  a1.txt  cmpt_error.h  makefile

The output of ls is printed to the screen, which is known as standard output. In C++, functions like printf and cin always prints to standard output.

You can easily write the output of a command use the > re-direction operator:

$ ls > listing.txt
$ cat listing.txt
a1.h
a1_sol*
a1_sol.cpp
a1.txt
cmpt_error.h
listing.txt
makefile

The command ls > listing.txt re-directs the standard output of ls into the file listing.txt.

You can also re-direct standard input. That means you can, for example, use a text file of input as the input to a program that reads from standard input (i.e. the keyboard).

Suppose the program ./age asks the user for their name and age. You could run it like this:

$ ./age
What's your name? Bob
How old are you? 20

Hi Bob, 20 is a great age!

The program waits while the user types Chris (and then presses return), and also while the user types 21 (and then presses return).

Another way to run this program is to first create a file called, say, test_input.txt with this content:

Chris 21

Then you can use the < re-direction operator to have ./age get its input from test_input.txt:

$ ./age < sample_input.txt
What's your name? How old are you?
Hi Bob, 20 is a great age!

This can be very useful for testing — it saves a lot of typing!