Basic Unix

From CS 61A Wiki
Revision as of 11:57, 5 June 2014 by Axis (Talk | contribs)


Jump to: navigation, search

This is a list of useful Unix commands.

Directories

A directory is a folder.

Current working directory

The current working directory is printed just before the command prompt (usually # or $):

~/test $

Alternatively, use the command pwd:

~/test $ pwd
~/test

Changing directory

The cd command changes the working directory.

When used with an argument, it changes to that directory:

~ $ cd test
~/test $ cd .. # .. is shorthand for "the parent directory"
~ $

When used without an argument, it changes to the home directory (~):

~/test $ cd
~ $

ls

ls lists the files in the current working directory.

Creation

To create a directory in the current directory, use the command mkdir:

~ $ ls $ nothing in the directory right now
~ $ mkdir test
~ $ ls
test
~ $ mkdir test2
~ $ ls
test  test2

Deletion

To delete a directory (along with all its contents), use the command rm -r:

~ $ ls
test  test2
~ $ rm -r test
~ $ ls
test2

Files

Creation

To create an empty file, use the touch command:

~ $ ls
test
~ $ touch my_file
~ $ ls
my_file  test

To create a file with predetermined text, use echo text > file:

~ $ echo testing > my_file
~ $ cat my_file
testing

This is called output redirection because the output of the command echo testing is sent to a file instead of being displayed on the screen.

cat

To view the contents of a file, use the cat command. See example above.

Deletion

To delete a file, use the rm command:

~ $ ls
my_file  test
~ $ rm my_file
~ $ ls
test

Copying

To copy a file, use the cp command:

~ $ ls
my_file  test
~ $ cat my_file
testing
~ $ cp my_file new_file
~ $ ls
my_file  new_file  test
~ $ cat new_file
testing

An example of copying a file from another directory:

~ $ ls
my_file  test
~ $ cp ~cs61a/lib/shakespeare.txt . # '.' is shorthand for "the current directory"
~ $ ls
my_file  shakespeare.txt  test

Renaming

To rename a file, use the mv command, where the first argument is the file you want to rename and the second argument is the new file name:

~ $ ls
my_file  test
~ $ mv my_file new_name
~ $ ls
new_name  test

Moving

To move a file to another directory, use the mv command, where the first argument is the file you want to move and the second argument is the destination directory:

~ $ ls
my_file  test
~ $ mv my_file test
~ $ ls
test
~ $ cd test
~ $ ls
my_file

Manual

The man command tells you how to use a Unix command. For example, man cp will bring up a page inside of the terminal. The NAME field will give a brief description of what the command does, and the DESCRIPTION will have a host of extra options you can run the command with.

You can navigate forward through the man page with the Enter/Return key and you can quit with q.

Sources