Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

Unix Notes

Unix is a multi-user, multi-tasking operating system that requires user authentication upon startup. It features a command-line interface (shell) for user interaction, supports various utilities for file management, and allows for remote connections via SSH. Understanding processes, commands, and utilities is essential for effective Unix usage.

Uploaded by

ibrahimsow367
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Unix Notes

Unix is a multi-user, multi-tasking operating system that requires user authentication upon startup. It features a command-line interface (shell) for user interaction, supports various utilities for file management, and allows for remote connections via SSH. Understanding processes, commands, and utilities is essential for effective Unix usage.

Uploaded by

ibrahimsow367
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

Unix

Unix Overview (Making Sense of It)


Unix is a powerful, multi-user, multi-tasking operating system with a simple yet
efficient design.

What happens when you start Unix?


When you start Unix, you are prompted to enter a username and password. This
process ensures only authorized users can access the system.

User Information:
Each user on a Unix system has:

A name: Your unique identifier.

A group: Users can be grouped together to manage permissions more easily.

A password: For security purposes.

A startup shell: The command-line interface you interact with (e.g., bash , sh ).

A home directory: The personal space allocated to you, usually located at


/home/<username> .

Why Unix is Unique:


Multi-user: Multiple people can work on the same system simultaneously
without interfering with each other.

Multi-tasking: Can run several programs at once.

Small Kernel: The core part of Unix is minimal, making it efficient.

Powerful Utilities: Comes with simple yet powerful tools for various tasks.

Highly Configurable: You can customize your environment through


configuration files.

Unix 1
Terminals, Shells, and Basic Commands
(Making Sense of It)
What happens after you log in?
Once you successfully log in, Unix starts a shell — a program that lets you interact
with the operating system by typing commands.

What is a Shell?
A shell is essentially a command-line interpreter. It takes your commands,
interprets them, and tells the operating system what to do. There are different
types of shells, including:

bash (Bourne Again Shell - the most common one).

sh (Original Bourne Shell).

csh (C Shell).

ksh (Korn Shell).

Types of Terminals:
1. Local Terminal:

A terminal directly connected to your local machine.

You type commands, and they are processed by the machine you're
working on.

2. Remote Terminal (via SSH):

Allows you to connect to another machine over a network.

Uses SSH (Secure Shell) for secure communication.

Example command:

bash
CopyEdit

Unix 2
ssh user@remote_host

This logs you into a remote machine securely.

How Commands Work:


Commands interact with the kernel (the core of the operating system) to
perform tasks.

Some commands are internal (built into the shell), while others are external
(separate programs).

Using the man Command:


The man command is your go-to tool for learning about other commands.

It displays a manual page with detailed descriptions and options for


commands.

Example:

bash
CopyEdit
man ls

This will show you everything you need to know about the ls command.

To search for commands by keyword, you can use:

bash
CopyEdit
man -k <keyword>

Example:

Unix 3
bash
CopyEdit
man -k copy

This shows all commands related to copying files or data.

Commands are Case-Sensitive:


Unix commands are almost always written in lowercase. If you type a command in
uppercase, it probably won’t work.

Flags (Options):
Flags modify the behavior of commands and usually start with a (dash).

Example:

The
l flag makes ls display files in a detailed list format.

bash
CopyEdit
ls -l

Multiple flags can be combined, like:

This lists all files (


a ) in a detailed format ( l ).

bash
CopyEdit
ls -la

Unix 4
Common Commands and What They Do:

Command What It Does

Lists directories and their contents recursively, showing all files


ls -Rxla
with detailed info.
cd <dir> Changes to the specified directory.
pwd Prints the current working directory.
passwd Changes your password.
sudo <command> Executes a command with superuser (root) privileges.
sudo apt-get install
Installs software packages (common on Ubuntu systems).
<package>

Why This Matters:

Understanding how shells and commands work is essential for interacting with
Unix. Whether you're running commands locally or over SSH, it's all about
communicating with the operating system via the shell.

Useful Utilities (Making Sense of It)


Unix comes with a set of simple yet powerful programs called utilities. They
mostly work by reading from stdin (standard input) and writing to stdout
(standard output). This makes them perfect for combining with other commands
using pipes ( | ).

What are Utilities?


Utilities are small programs designed to perform specific tasks. They often work
by reading from files or user input and writing results to the screen or a file.

Common Utilities and Their Purpose:


Utility What It Does Example Usage

Unix 5
sort Sorts lines in a file alphabetically or numerically. sort names.txt

Removes duplicate lines from input (requires


uniq `sort names.txt
sorted input).

Searches for files that match certain criteria and


find find . -name "*.java"
allows operations on them.
grep Searches files for specific patterns. grep "error" logfile.txt

wc Counts lines, words, and characters in files. wc -l file.txt

Updates a file's access and modification time, or


touch touch newfile.txt
creates an empty file if it doesn't exist.

Displays the first ( head ) or last ( tail ) lines of a head -5 file.txt / tail -5
head / tail
file. file.txt

Displays file contents. Often used to combine cat file1.txt file2.txt >
cat
files. combined.txt

Views files one page at a time ( less is better for


more / less less bigfile.txt
large files).

Understanding Utilities with Examples:


1. Sorting Files:

bash
CopyEdit
sort students.txt

This command reads the contents of students.txt and displays them in


alphabetical order.

2. Removing Duplicates:

bash
CopyEdit
sort students.txt | uniq

Unix 6
The uniq command only removes consecutive duplicates, so we use sort to
order them first.

3. Finding Files:

bash
CopyEdit
find . -name "*.java"

This searches the current directory ( . ) and all its subdirectories for files
ending in .java .

4. Searching Files for Patterns:

bash
CopyEdit
grep "error" logfile.txt

Searches for the word "error" in logfile.txt and displays the matching lines.

5. Counting Lines in a File:

bash
CopyEdit
wc -l file.txt

Displays the number of lines in file.txt .

6. Viewing the Start or End of a File:

bash
CopyEdit
head -10 file.txt

Unix 7
tail -10 file.txt

Shows the first or last 10 lines of file.txt .

7. Creating/Updating a File with touch :

bash
CopyEdit
touch notes.txt

If notes.txt exists, it updates the access/modification time.

If it doesn't exist, it creates an empty file called notes.txt .

8. Viewing Files Page-by-Page:

bash
CopyEdit
less bigfile.txt

Opens bigfile.txt one screen at a time, allowing you to scroll back and forth.

Use q to quit.

Why This Matters:


These utilities are the building blocks of working with Unix. They can be used on
their own or combined in powerful ways using pipes and redirection to manipulate
files, extract information, and automate tasks.

Unix 8
Compressing Files & Archives (Making
Sense of It)
In Unix, you often need to archive files (group them into one file) and compress
files (reduce their size) to save space or prepare them for transfer.

Creating Archives with tar :


The tar command is the most common tool used for creating and managing
archives (also known as tarballs).

Basic tar Commands:

Command What It Does Example Usage

tar -cvf <archive_name> Creates an archive without


tar -cvf archive.tar mydir/
<files/dirs> compression.

tar -czvf <archive_name> Creates a compressed archive tar -czvf archive.tar.gz


<files/dirs> using gzip . mydir/

tar -tvf <archive> Lists the contents of an archive. tar -tvf archive.tar.gz

tar -xvf <archive> Extracts files from an archive. tar -xvf archive.tar.gz

What the Flags Mean:


c : Create an archive.

v : Verbose mode (shows what’s happening).

f : Specifies the name of the archive file.

z : Compresses the archive using gzip (creating .tar.gz files).

t : Lists files in an archive without extracting them.

x : Extracts files from an archive.

Examples of Using tar :


1. Creating an Archive (Without Compression):
This bundles

Unix 9
file1.txt , file2.txt , and the folder folder/ into an archive called myfiles.tar .

bash
CopyEdit
tar -cvf myfiles.tar file1.txt file2.txt folder/

1. Creating a Compressed Archive (With gzip ):


Same as above, but the archive is compressed, saving space. The
.gz extension indicates compression.

bash
CopyEdit
tar -czvf myfiles.tar.gz file1.txt file2.txt folder/

1. Listing Archive Contents:


Shows all files and folders within the compressed archive.

bash
CopyEdit
tar -tvf myfiles.tar.gz

1. Extracting Files from an Archive:


Extracts all files from the archive into the current directory.

bash
CopyEdit
tar -xvf myfiles.tar.gz

Using Compression Tools (Without tar ):

Unix 10
Sometimes you only need to compress a single file.

Command What It Does Example Usage


gzip <file> Compresses a file, replacing it with <file>.gz . gzip bigfile.txt

gunzip <file> Decompresses a .gz file. gunzip bigfile.txt.gz

bzip2 <file> Compresses a file more efficiently than gzip . bzip2 bigfile.txt

bunzip2 <file> Decompresses a .bz2 file. bunzip2 bigfile.txt.bz2

When to Use gzip vs. bzip2 :


gzip : Faster, but less compression.

bzip2 : Slower, but better compression (saves more space).

Why This Matters:


Archiving makes it easier to move multiple files as a single package.

Compressing saves disk space and speeds up file transfers.

Using tar combined with gzip or bzip2 is standard practice for backing up or
sharing files in Unix.

Processes

Processes (Making Sense of It)


A process is simply a program that is currently running on the system. Every time
you run a command or open a program, a process is created.

What is a Process?
Program in Execution: It’s a running instance of a program (like a text editor, a
game, or a compiler).

Unix 11
Unique Identifier (PID): Every process has a unique Process ID (PID).

Own Address Space: It gets its own memory space to prevent interference
with other processes.

Communication: Processes can communicate using mechanisms known as


IPC (Inter-Process Communication).

Process Priorities (nice and renice):


Unix allows you to control the priority of processes to ensure the system is
efficient.

nice Command:
Sets the initial priority of a process when you start it.

A lower priority allows other processes to run first (i.e., you are being “nice” to
others).

Default priority: 0 (normal).

Range: -20 (highest priority) to 19 (lowest priority).

Example:

This starts
myprogram with a lower priority of 10 .

bash
CopyEdit
nice -n 10 myprogram

renice Command:
Changes the priority of a process that’s already running.

Example:

Unix 12
This sets the priority of the process with PID
1234 to 5 (higher priority).

bash
CopyEdit
renice -5 -p 1234

Viewing Processes:
There are several ways to check what processes are running.

Command What It Does Example Usage


ps Shows running processes. ps -al

Continuously displays active processes and their


top top
resource usage.
who Lists users currently logged into the system. who

finger <user> Displays information about a specific user. finger alice

Understanding the ps Command:


Shows information about processes currently running in your session.

Example:

bash
CopyEdit
ps -al

a : Shows processes of all users.

l : Provides detailed (long) listing.

Typical output:

Unix 13
objectivec
CopyEdit
F UID PID PPID C STIME TTY TIME CMD
4 1000 12345 1 0 10:00 pts/0 00:00:01 bash
4 1000 12346 12345 0 10:05 pts/0 00:00:02 vim

UID: User ID of the process owner.

PID: Process ID.

PPID: Parent Process ID (The process that started this process).

CMD: Command name.

Understanding the top Command:


Continuously updates a list of active processes.

Shows real-time information about CPU and memory usage.

Press q to quit.

Why This Matters:


Understanding how processes work helps you monitor and control what's
running on your system.

Knowing how to adjust process priorities can make sure critical tasks run
smoothly.

Commands like ps and top are essential for system monitoring and
troubleshooting.

Info about the system state

who - list of user logged onto the host

Unix 14
ps - list of processes(lots of options. e.g. ps -al (a-all users, l = long listing))

finger X - get info on user with login X

top - constantly updating list of process on system

Working on remote machines


Working on Remote Machines (Making Sense of It)
Unix systems allow you to connect to and work on remote systems over a
network. This is useful when you need to access files, run programs, or manage
systems that aren’t directly in front of you.

What is SSH? (Secure SHell)


SSH is a protocol used to securely log into a remote machine over a network.

It encrypts your connection, making it safe to use even over public networks.

Replaces older, insecure protocols like telnet .

Connecting to a Remote Machine with SSH:


To start an SSH session:

bash
CopyEdit
ssh user@remote_host

user : Your username on the remote machine.

remote_host : The IP address or hostname of the remote machine.

Example:

Unix 15
bash
CopyEdit
ssh alice@192.168.1.10

This will connect you to the machine at IP address 192.168.1.10 as the user alice .

Tools for SSH:


Linux/Mac: You can use the terminal directly.

Windows:

Use software like Putty (a free SSH client) or the built-in Windows
Terminal (if OpenSSH is installed).

What is sFTP? (Secure File Transfer Protocol)


sFTP is a secure way to transfer files between your machine and a remote
machine.

Works similarly to SSH but is designed specifically for file transfers.

Encrypts the data being transferred, making it secure.

Starting an sFTP Session:

bash
CopyEdit
sftp user@remote_host

Example:

bash
CopyEdit

Unix 16
sftp alice@192.168.1.10

This will start an sFTP session with the remote machine.

Common sFTP Commands:


Command What It Does Example Usage

Lists files in the current directory on the remote


ls ls
machine.

Prints the current working directory on the remote


pwd pwd
machine.
cd <directory> Changes directory on the remote machine. cd /home/alice

Uploads a file from your local machine to the remote


put <file> put myfile.txt
machine.

Downloads a file from the remote machine to your local


get <file> get notes.txt
machine.
mput <files> Uploads multiple files at once. mput *.txt

mget <files> Downloads multiple files at once. mget *.java

close Ends the sFTP session but keeps the terminal open. close

exit Ends the sFTP session and closes the terminal. exit

Example sFTP Session:

bash
CopyEdit
sftp alice@192.168.1.10
Password: *****

sftp> ls
Documents Pictures Music

sftp> cd Documents
sftp> put myfile.txt

Unix 17
Uploading myfile.txt to /home/alice/Documents/myfile.txt

sftp> get homework.doc


Downloading homework.doc to ./homework.doc

sftp> exit

Why This Matters:


SSH allows you to remotely manage systems, which is critical for servers and
remote devices.

sFTP makes it easy to transfer files securely without worrying about data
being intercepted.

Knowing how to use these tools gives you control over systems even when
you’re not physically present.

The Unix File System


File System Structure: Files and directories are organized in a hierarchical
structure, and the physical storage can be located across a network.

Directories: In Unix, directories are special types of files.

File Storage: Files are made up of fixed-size blocks (typically 0.5–4KB).

File Information: Use the ls -l command to view file information such as


inodes (file identifiers) and links (references to files).

Links:

Hard links create another reference to the same file.

Soft (Symbolic) links are essentially "shortcuts" to a file or directory. Use


ln -s file1 file2 to create a soft link.

Unix 18
Disk Usage: Use the du command to check disk usage.

File System Space: Use df [filesystem] to check available disk space on a


filesystem.

Directory and File Commands


Copy Command ( cp ):

cp A B : Copy file A to B .

cp -r : Use r to copy directories recursively.

Example: cp ../file2.txt . copies file2.txt from the parent directory into the
current directory.

Rename or Move ( mv ): Used to rename or move files or directories.

Create Directory ( mkdir ): Creates a new directory.

Remove File ( rm ): Deletes files.

rm -r : Recursively delete a directory and its contents.

Remove Empty Directory ( rmdir ): Removes an empty directory.

Device Files
Device Files: In Unix, device files are special files that provide interfaces to
hardware devices.

File Types: You can check the type of a file with the ls -l command (the first
character indicates whether it’s a regular file, directory, or device file).

Examples of Device Files:

/dev/null : A special device where data written is discarded.

/dev/audio : Device for playing sound.

/dev/console , /dev/ttyN : Console and terminal devices.

I/O Redirection

Unix 19
Standard Streams: Every process has three standard streams—stdin (input),
stdout (output), and stderr (error output).

Redirection Operators:

< : Redirect input from a file (e.g., sort < inputfile reads from inputfile ).

> : Redirect output to a file (e.g., sort > outputfile writes sorted data to
outputfile ).

>> : Append output to a file (e.g., cat file1 >> file2 appends file1 content to
file2 ).

<<: Allows reading multiple lines from stdin (e.g., sort <<EOF allows input
until EOF is typed).

Examples:

more < file.txt : Displays file.txt page by page.

ls -l > file.txt : Lists the current directory’s files and writes the output to file.txt .

cat > file.txt : Creates a file called file.txt with no editor.

I/O Piping
Piping ( | ): Piping connects the output of one command to the input of
another command.

Example: cat myfile | sort | uniq | grep CSI > output sorts the content of myfile ,
removes duplicates, and then filters for the term CSI , saving the result in
output .

Redirection with Piping: You can combine redirection with piping. Example:
gzip -dc archive.tar.gz | tar -xvf - > /dev/null decompresses and extracts an archive,

sending all output to /dev/null (essentially discarding it).

Stderr: By default, stderr writes to the terminal unless redirected.

Aliases
Creating Aliases: You can create aliases to make commands shorter or more
convenient.

Unix 20
Example: alias dir='ls -lF' makes dir behave like ls -lF in the KornShell (ksh).

File permissions(Protecting your files)


File Permissions Overview
1. Permission Sets:

Three sets of permissions:

User (owner)

Group (users in the file's group)

World/Others (everyone else)

2. Permission Types:

r (read): View file contents.

w (write): Modify file contents.

x (execute): Run the file as a program.

For directories, x means you can enter ( cd ) into the directory.

(not set): No permission.

Permission String Format


When you do:

bash
CopyEdit
ls -l myfile.dat

You get something like:

diff
CopyEdit

Unix 21
-rwxr-xr-x 1 userid gid 10 Feb 15 09:00 myfile.dat

= File type ( for file, d for directory, etc.)

rwxr-xr-x = Permissions (User, Group, World)

1 = Number of links

userid = Owner of the file

gid = Group name

10 = File size (bytes)

Feb 15 09:00 = Modification date and time

myfile.dat = File name

Octal Mapping of Permissions


Permissions can be represented using numbers:

Permission Binary Octal

r (read) 100 4

w (write) 010 2

x (execute) 001 1

The permissions are represented as a sum of these numbers.

For example, rwx (read, write, execute) = 4+2+1=7 .

Example
Permission string:

CopyEdit
r-xr-xrwx

Binary representation:

Unix 22
CopyEdit
101 101 111

Octal calculation:

CopyEdit
4+1, 4+1, 4+2+1 = 557 (octal)

Changing Permissions
Using chmod :

Symbolic form:

bash
CopyEdit
chmod og+w myfile # Adds write permission to group & others

Octal form:

bash
CopyEdit
chmod 777 myfile # Full permission for everyone

Changing file group access ( chgrp ):

bash
CopyEdit
chgrp groupname myfile

Unix 23
Usually, only root or the file owner can change the group.

Default File Creation Permissions ( umask )


umask sets default permissions when creating files/directories.

Works by applying a bitwise XOR operation to the permissions.

Example:

bash
CopyEdit
umask 022 # Files will be created with permissions 644 (rw-r--r--)

The Shell

Job Control
Job control allows you to manage multiple processes running in the
background or foreground within a shell session.

Shell Execution Environment: The shell provides the environment in which


commands and processes run.

Jobs:

bg: Move a job to the background (so it runs without blocking your
terminal).

fg: Bring a background job to the foreground (to interact with it


directly).

kill: Terminate a running job by its job ID.

^Z (CTRL-Z): Suspend the current job running in the foreground


(effectively pausing it).

&: Run a command in the background immediately.

Unix 24
jobs: List all jobs running in the background or suspended.

Customization
Environment Variables: These are variables that influence the behavior of the
shell and programs. Some common ones are:

PATH : Specifies directories for the shell to search for executables.

HOME : The home directory of the user.

Shell Initialization Files: These files are executed when you start a new shell
session and can customize your shell environment:

, .login , .profile : These files are shell-specific configuration files that


.shrc

you can modify to set up your environment (e.g., aliases, environment


variables).

Changing the Default Editor:

For tcsh or csh : setenv EDITOR emacs sets the default editor to emacs .

For ksh or bash : export EDITOR=emacs does the same.

Default Shell: The default shell for a user is set by the root user, often in
/etc/passwd .

Metacharacters
Metacharacters are special characters in the shell that have a specific
meaning:

: Wildcard used to match any number of characters in filenames.

? : Wildcard used to match a single character in filenames.

; : Separates commands, allowing you to run multiple commands on one


line.

{} : Used for grouping commands or expanding arguments.

() : Used to create a subshell to run commands in isolation.

Spaces: Used to separate input arguments or filenames in a command.


Filenames with spaces need to be enclosed in quotes (e.g., "my file" ).

Unix 25
Escaping Special Characters: To prevent special characters from being
interpreted by the shell, you can escape them with a backslash ( \ ). For
example, \* , \; will treat and ; as literal characters, not as
metacharacters.

Scripts
Shell Scripts: A script is a file that contains a series of commands that the
shell can execute.

Purpose: Scripts help automate tasks, define new commands, and execute
repetitive actions. They can be written interactively or as standalone files.

Customization: You can use scripts to further customize your shell


environment and streamline processes.

Syntax: The syntax depends on the shell being used. For example, the
Bash shell syntax is different from the KornShell ( ksh ) or C shell ( csh ). Use
man bash to read more about Bash scripting.

Common Usage: Shell scripts are heavily used in system administration to


automate tasks like backups, file management, and software installation.

Example: Bash Shell Script 1

#!/bin/bash

# Script: check for at least 3

# files called nameN

NAME=name*

COUNT=`ls -l $NAME | wc-l`


if [ $COUNT -lt3 ]; then

Unix 26
echo "Too few files: " $COUNT
else
echo "OK -Number files: " $COUNTfi
#must chmod u+x script

Bash Shell

Script comments
a variable is defined in the “for” loop

To access the variable f, use $f

to set its value leave off $

values are all text strings

echo - prints text to the screen

any command can appear in a scipt

#! tells OS what shell to use for script

‘ ‘ captures the output from a command

Basic Control Settings

if [expression]; then
command
elif
command
else
command

Unix 27
fi

for var in list; do


command
done

example 2

#!/bin/bash
#
# Script: check for 3 files as
# command line args and display their content
# $1 is arg1; $*is list of all command line args;
# $#number args
if [ $# != 3 ]; then
echo "Incorrect file number: " $#
else
for f in $*; do
echo "File: " $f
echo " -contains: "
cat $f
done
fi

Development Tools
Text Editors
vi/vim, emacs, joe: These are popular text editors used in Unix-based
environments for editing source code and other files.

Unix 28
vi/vim: A powerful and widely-used text editor with modes for inserting
text and running commands.

emacs: A highly customizable and extensible text editor, often favored for
its advanced features.

joe: A simpler, easier-to-use text editor compared to vi and emacs.

Compilers
javac: The Java compiler that translates Java source code into bytecode.

JVM (Java Virtual Machine): A virtual machine that runs Java bytecode,
making Java programs platform-independent.

java: The command used to run Java programs by executing the bytecode
produced by javac .

Makefile for Projects


Makefiles are used to manage and automate the building of software projects,
particularly for large projects with multiple source files. They specify
dependencies and rules for compiling and linking files efficiently.

Naive Approach: Manually recompiling all project files whenever one file is
changed is inefficient.

Automating Dependencies: Makefiles use dependency checks to only


recompile the parts of the project that have changed. This is often done by
comparing timestamps.

Building Java Projects


Ant (from Apache): A Java-based build tool that uses XML to define
dependencies and build instructions.

Pros: It’s tailored for Java and handles dependencies for inner classes and
packages very well.

Cons: Since it’s Java-based, it might not be available on all Unix systems
by default.

Unix 29
Make: A widely-used Unix tool for managing project dependencies and
automating builds. It uses a configuration file (Makefile) to define rules for
building targets and their dependencies.

Pros: It works well with C++ and large open-source projects, and it’s often
available on Unix systems as GNU Make (gmake).

Cons: It can struggle with Java projects due to inner class/package


dependencies and non-one-to-one mappings between targets and
dependencies.

The Make Utility


Using make : The make command automatically builds targets by using rules
defined in a Makefile. It checks for changes in dependencies and rebuilds only
those files that are affected.

Command: After editing source code, you just run make to ensure the
project is up to date.

Makefile Example:

This Makefile specifies that


HelloWorld.class depends on HelloWorld.java , and if the Java source file changes,
it will trigger a rebuild of the class file by running the javac command.

makefile
CopyEdit
HelloWorld.class : HelloWorld.java
javac HelloWorld.java

Makefile Configuration: The Makefile contains rules that specify which files
are dependencies and how to update them when the source files change.

Syntax: A rule in the Makefile follows this structure:

For example, if

Unix 30
is modified, the Makefile ensures that
HelloWorld.java HelloWorld.class is
recompiled by executing javac HelloWorld.java .

yaml
CopyEdit
target : dependency_list
target_action

Makefile Usage:

Use the default Makefile: make

Use a custom Makefile: make -f makefile_name

Makefiles can contain various rules and options, and even scripting
commands.

Important Notes for Makefiles:


Tabs vs. Spaces: In Makefiles, you must use tabs (not spaces) at the
beginning of rule actions. This is crucial—if you use spaces, the build will fail.

Rule Types: Makefiles can include various types of rules to handle different
tasks, such as cleaning up old files ( clean ), compiling, and linking.

Efficiency: If the Makefile is set up correctly, only the modified files will be
rebuilt, saving time in large projects.

Key Concepts Recap:


Automating Builds: Using tools like make and Ant to automatically handle
dependencies and build projects efficiently.

Dependencies: Ensure that only changed files are rebuilt, improving


performance.

Makefile Syntax: Learn the structure of Makefiles to specify dependencies


and actions correctly.

Text Editors: Use editors like vi , vim , or emacs for writing code in a Unix
environment.

Unix 31
Variables
Makefiles allow you to define variables to simplify configuration and avoid hard-
coding paths and commands. For example, the variable JAVAC is used to store the
path to the Java compiler”

JAVAC=/user/bin/javac

This means, instead of writing /usr/bin/javac everywhere in Makefile, you can use
$(JAVAC) to refer to the Java compiler

Rules with variables


You can then use the variable in rules. For example:

Womble.class: Womble.java
$(JAVAC) $(JFLAGS) Womble.java

This tells Make to create Womble.class from Womble.java by using the Java
compiler stored in JAVAC and any flags stored in JFLAGS. If JFLAGS is set
somewhere else in the Makefile, it would pass those flags to the computer

Built-in Rules and Macros


Makefiles also have built-in rules for common tasks like compiling .java files into
.class files> For example

.java:class: $(JAVAC) $<

This is a built in rule that tells Make how to convert .java files into .class files. The
$< is a special macro that refers to the first prerequisite(the .java file in this case).
So if you have a .java file, Make will use the rule to create a .class file

Unix 32
Using .SUFFIXES
If you want to exlicitily define which suffixes Make should use,you can set the
.SUFFIXES variable

.SUFFIXES: .java .class

This tells Make that it should consider .java and .class as valid file suffixes when
applying rules

String Substitution
Makefiles also allow you to do string substitution with variables. This is useful
when you have a list of files and you want to convert one type to another(like
converting .java files into .class)

SOURCES = A.java B.java C.java


OBJECTS = $(SOURCES:.java=.class)

This uses string submission to convert .java extensions into .class. The resulting
value of OBJECTS would be A.class B.class C.class

example

# Define variables
JAVAC = /usr/bin/javac
JFLAGS = -g
SOURCES = A.java B.java C.java
OBJECTS = $(SOURCES:.java=.class)

# Default rule
all: $(OBJECTS)

# Rule to compile .java files into .class files


.java.class:

Unix 33
$(JAVAC) $(JFLAGS) $<

# Clean rule
clean:
rm -f $(OBJECTS)

the all taget compiles A.java B.java and C.java into their respective .class files

The rule .java.class defines how to convert a .java file into a .class file using
the javac compiler

the clean target removes all the .class files

Makefiles: More Information


1. Makefile Formatting:

No space after text on a line: After you type your rule or command, press
<RETURN> (enter) to move to the next line.

Tab for indenting rules: Rules inside a Makefile must be indented with a
tab, not spaces.

@ symbol: Use the @ symbol before a command to suppress the echo of


the rule while it executes (i.e., it won’t print out the command).

2. Rule Evaluation:

If no target is specified, the first rule in the Makefile is evaluated by


default.

You can create a target with no dependencies. For example, a common


one is clean , which is often used to remove temporary files.

Example:

makefile
CopyEdit
clean:

Unix 34
rm *.class

This clean target will delete all .class files when you run make clean from the
command line.

3. Including Files:

You can include other files in a Makefile using the include statement. This
helps keep Makefiles organized and reusable.

Makefile Example 1 (Messy Makefile):

makefile
CopyEdit
# Messy Makefile
JAVAC = javac
JFLAGS = -g
JARFILE = blah.jar
CLASSFILES = A.class B.class C.class

# Default rule
C.class: A.class B.class C.java
$(JAVAC) $(JFLAGS) C.java

# Other explicit build rules


A.class: A.java
$(JAVAC) $(JFLAGS) A.java

B.class: B.java
$(JAVAC) $(JFLAGS) B.java

# Explicit rules
clean:
@rm -f $(CLASSFILES)

jar:

Unix 35
jar cvf $(JARFILE) $(CLASSFILES)

In this example:

The clean target removes all .class files.

The jar target creates a JAR file from the .class files.

Makefile Example 2 (Better Makefile):

makefile
CopyEdit
# Better Makefile
JAVAC = javac
JFLAGS = -g
SOURCES = A.java B.java C.java

# Define a general build rule for Java sources.


SUFFIXES: .java .class
.java.class:
$(JAVAC) $(JFLAGS) $<

# Default rule will be invoked by `make` (no build rule required).


C.class: A.class B.class C.java

# Explicit rules (string substitution from .java to .class)


clean:
@rm -f $(SOURCES:.java=.class)

In this example:

The SUFFIXES line defines how files with the .java extension should be treated
and compiled into .class files.

The clean target removes all .class files based on .java files in the SOURCES list.

Unix 36
Git: Version Control System
Why Git?

Managing code updates on large projects can be tedious and error-prone,


especially with multiple contributors.

Git is a lightweight and powerful version control system that helps track
changes in the source code over time.

Key Features of Git:

Maintains a code repository (repo): It stores all the code and logs, recording
all committed updates.

Works with multiple contributors: Multiple people can work on the same
project simultaneously, and Git helps manage changes from all team
members.

History and Rollback: You can go back in time, revert code to previous
versions, and track the history of changes.

Advantages:

1. Branching and Merging: You can explore alternative solutions by creating


branches and later merge them back into the main codebase.

2. Remote Repositories: Git allows you to store your code repository on remote
servers, so you can access it from anywhere on the Internet. (Though this may
not be required in your current course, it’s common in larger projects.)

3. Rewind Code: You can revert to any commit in the history if something goes
wrong.

4. Team Collaboration: Git allows multiple people to work on the same project at
the same time without conflict.

Why Use Git in Industry:

Source Control: Git is a standard tool in the software industry for managing
large and collaborative projects. It’s crucial to know how to use Git effectively
in the workplace.

Other Version Control Systems:

Unix 37
CVS, Subversion, and Mercurial are alternatives to Git, though Git is the most
widely used and favored for its speed and flexibility.

Basic Git Terminology:


1. Repository (Repo): A directory where your source code is stored, along with
special Git management files that track the version history.

2. Branch: A separate version of your codebase. It allows you to explore or test


new features without affecting the main project.

3. Add: The action of adding new files or changes to existing files to the "staging
area". This prepares them for later committing to the repository.

You can also unstage changes if you decide not to commit them.

4. Commit: This action adds your staged changes to the repository, with a
commit message explaining the changes made. This makes a snapshot of your
project at that point.

5. Checkout: Used to switch between branches or retrieve previous versions of


files. This allows you to work on different versions of the project.

Starting with Git:


1. Set your identity for all Git projects:

bash
CopyEdit
git config --global user.name "Joe Blogs"
git config --global user.email joe@whatever

2. Create a repository:

Navigate to the directory where you want your project:

bash
CopyEdit
mkdir Prac0

Unix 38
cd Prac0
git init

3. Basic Git workflow:

Create and edit files in your repo directory.

Stage changes using git add .

Commit changes with git commit .

4. Check the status of files Git is tracking:

Use git status to check which files are modified and which are staged for
commit.

5. Optional:

Remove unwanted files: You can delete files or directories using git rm .

Create branches to experiment with new ideas.

Merge branches when you are ready to bring changes from one branch to
another.

Recover previous file versions using git checkout or by reverting to previous


commits.

Git Structure:
Working Directory: The files and directories you are working on in your
project. These are your physical files.

Staging Area: An index that keeps track of changes made to files, staging
them for the next commit.

Commit History: A sequence of commits (snapshots of your project) that you


can navigate through.

How Git Works:


Every commit in Git is a snapshot of your code at a specific point in time.

Unix 39
Staged changes are included in the snapshot, but unstaged changes are
not.

Unchanged tracked files will still be included in the commit.

Git HEAD: This is an internal pointer to the last commit on your current branch.
When you switch branches with git checkout , the HEAD pointer shifts to the new
branch.

Example Workflow in Git:


1. Set up repo and add files:

Create a directory for your project:

bash
CopyEdit
mkdir Prac0
cd Prac0
git init

Edit files (e.g., myfile.java ) and stage them:

bash
CopyEdit
git add myfile.java

Stage multiple files (wildcards work as well):

bash
CopyEdit
git add *.java

2. Check the status of files:

Unix 40
git status will show the files you’ve modified, added, or deleted.

3. Commit changes:

Commit your staged changes:

bash
CopyEdit
git commit -m "Add initial version of myfile.java"

Use git log to see the history of commits, and git log --oneline for a one-line
summary of each commit.

4. Remove files from the directory and repo:

To delete a file and commit the change:

bash
CopyEdit
git rm a.java
git commit -m "Remove a.java from repo"

To delete a whole directory:

bash
CopyEdit
git rm -r dir
git commit -m "Remove directory dir"

Key Git Commands:


git status : Shows the current status of your working directory and staging area.

git add : Stages changes for the next commit.

git commit : Commits the staged changes to the repository with a message.

Unix 41
git log : Shows the commit history.

git log --oneline : Displays the commit history in a more compact format (one line
per commit).

git rm : Removes a file from the repository and working directory.

Setting Up Git on Ubuntu:


If Git is not installed on your Ubuntu system, you can install it by running:

bash
CopyEdit
sudo apt-get install git

Unix 42

You might also like