Archive for the ‘ How-To's ’ Category

Tip: Perl Script to Archive Log Files

This is a simple Perl script I wrote to search a given directory for *.log files, tag with the current date and archive them.

#!/usr/bin/perl

$DIR=”/var/www/html/sites/logs”;
$DATE=`date +%F`;
chomp $DATE;

@log = `/usr/bin/find $DIR -type f -name “*.log” `;

#print “\nRotating $DATE\n”;

foreach $log (@log) {
chomp $log;
$new_fn=”$log”.”-”.”$DATE”;
#print “$log $new_fn\n”;
`mv “$log” “$new_fn”`;

}

@raw=`/usr/bin/find $DIR -type f -name “*$DATE*”`;

foreach $raw (@raw) {
chomp $raw;
#print “$raw\n”;
`gzip -9 $raw`;

}

EDIT:

Modified version:

#!/usr/bin/perl

$DIR=”/var/www/html/sites/logs”;
$DATE=`date +%F`;
chomp $DATE;

@log = `/usr/bin/find $DIR -type f -name “*.log” `;

#print “\nRotating $DATE\n”;

foreach $log (@log) {
chomp $log;
$new_fn=”$log”.”-”.”$DATE”;
#print “$log $new_fn\n”;
`mv “$log” “$new_fn”`;
`gzip -9 $new_fn`;

}

Popularity: 11% [?]

10 Good Unix Habits

Adopt 10 good habits that improve your UNIX® command line efficiency — and break away from bad usage patterns in the process. This article takes you step-by-step through several good, but too often neglected, techniques for command-line operations. Learn about common errors and how to overcome them, so you can learn exactly why these UNIX habits are worth picking up.

Introduction

When you use a system often, you tend to fall into set usage patterns. Sometimes, you do not start the habit of doing things in the best possible way. Sometimes, you even pick up bad practices that lead to clutter and clumsiness. One of the best ways to correct such inadequacies is to conscientiously pick up good habits that counteract them. This article suggests 10 UNIX command-line habits worth picking up — good habits that help you break many common usage foibles and make you more productive at the command line in the process. Each habit is described in more detail following the list of good habits.

Adopt 10 good habits

Ten good habits to adopt are:

1. Make directory trees in a single swipe.
2. Change the path; do not move the archive.
3. Combine your commands with control operators.
4. Quote variables with caution.
5. Use escape sequences to manage long input.
6. Group your commands together in a list.
7. Use xargs outside of find.
8. Know when grep should do the counting — and when it should step aside.
9. Match certain fields in output, not just lines.
10. Stop piping cats.

Make directory trees in a single swipe

Listing 1 illustrates one of the most common bad UNIX habits around: defining directory trees one at a time.

Listing 1. Example of bad habit #1: Defining directory trees individually

~ $ mkdir tmp
~ $ cd tmp
~/tmp $ mkdir a
~/tmp $ cd a
~/tmp/a $ mkdir b
~/tmp/a $ cd b
~/tmp/a/b/ $ mkdir c
~/tmp/a/b/ $ cd c
~/tmp/a/b/c $

It is so much quicker to use the -p option to mkdir and make all parent directories along with their children in a single command. But even administrators who know about this option are still caught stepping through the subdirectories as they make them on the command line. It is worth your time to conscientiously pick up the good habit:

Listing 2. Example of good habit #1: Defining directory trees with one command

~ $ mkdir -p tmp/a/b/c

You can use this option to make entire complex directory trees, which are great to use inside scripts; not just simple hierarchies. For example:

Listing 3. Another example of good habit #1: Defining complex directory trees with one command

~ $ mkdir -p project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

In the past, the only excuse to define directories individually was that your mkdir implementation did not support this option, but this is no longer true on most systems. IBM, AIX®, mkdir, GNU mkdir, and others that conform to the Single UNIX Specification now have this option.

For the few systems that still lack the capability, use the mkdirhier script (see Resources), which is a wrapper for mkdir that does the same function:

~ $ mkdirhier project/{lib/ext,bin,src,doc/{html,info,pdf},demo/stat/a}

Change the path; do not move the archive

Another bad usage pattern is moving a .tar archive file to a certain directory because it happens to be the directory you want to extract it in. You never need to do this. You can unpack any .tar archive file into any directory you like — that is what the -C option is for. Use the -C option when unpacking an archive file to specify the directory to unpack it in:

Listing 4. Example of good habit #2: Using option -C to unpack a .tar archive file

~ $ tar xvf -C tmp/a/b/c newarc.tar.gz

Making a habit of using -C is preferable to moving the archive file to where you want to unpack it, changing to that directory, and only then extracting its contents — especially if the archive file belongs somewhere else.

Combine your commands with control operators

You probably already know that in most shells, you can combine commands on a single command line by placing a semicolon ( ; ) between them. The semicolon is a shell control operator, and while it is useful for stringing together multiple discrete commands on a single command line, it does not work for everything. For example, suppose you use a semicolon to combine two commands in which the proper execution of the second command depends entirely upon the successful completion of the first. If the first command does not exit as you expected, the second command still runs — and fails. Instead, use more appropriate control operators (some are described in this article). As long as your shell supports them, they are worth getting into the habit of using them.

Run a command only if another command returns a zero exit status

Use the && control operator to combine two commands so that the second is run only if the first command returns a zero exit status. In other words, if the first command runs successfully, the second command runs. If the first command fails, the second command does not run at all. For example:

Listing 5. Example of good habit #3: Combining commands with control operators

~ $ cd tmp/a/b/c && tar xvf ~/archive.tar

In this example, the contents of the archive are extracted into the ~/tmp/a/b/c directory unless that directory does not exist. If the directory does not exist, the tar command does not run, so nothing is extracted.
Run a command only if another command returns a non-zero exit status

Similarly, the || control operator separates two commands and runs the second command only if the first command returns a non-zero exit status. In other words, if the first command is successful, the second command does not run. If the first command fails, the second command does run. This operator is often used when testing for whether a given directory exists and, if not, it creates one:

Listing 6. Another example of good habit #3: Combining commands with control operators

~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c

You can also combine the control operators described in this section. Each works on the last command run:

Listing 7. A combined example of good habit #3: Combining commands with control operators

~ $ cd tmp/a/b/c || mkdir -p tmp/a/b/c && tar xvf -C tmp/a/b/c ~/archive.tar

Quote variables with caution

Always be careful with shell expansion and variable names. It is generally a good idea to enclose variable calls in double quotation marks, unless you have a good reason not to. Similarly, if you are directly following a variable name with alphanumeric text, be sure also to enclose the variable name in curly braces ({}) to distinguish it from the surrounding text. Otherwise, the shell interprets the trailing text as part of your variable name — and most likely returns a null value. Listing 8 provides examples of various quotation and non-quotation of variables and their effects.

Listing 8. Example of good habit #4: Quoting (and not quoting) a variable

~ $ ls tmp/
a b
~ $ VAR=”tmp/*”
~ $ echo $VAR
tmp/a tmp/b
~ $ echo “$VAR”
tmp/*
~ $ echo $VARa

~ $ echo “$VARa”

~ $ echo “${VAR}a”
tmp/*a
~ $ echo ${VAR}a
tmp/a
~ $

Use escape sequences to manage long input

You have probably seen code examples in which a backslash (\) continues a long line over to the next line, and you know that most shells treat what you type over successive lines joined by a backslash as one long line. However, you might not take advantage of this function on the command line as often as you can. The backslash is especially handy if your terminal does not handle multi-line wrapping properly or when your command line is smaller than usual (such as when you have a long path on the prompt). The backslash is also useful for making sense of long input lines as you type them, as in the following example:

Listing 9. Example of good habit #5: Using a backslash for long input

~ $ cd tmp/a/b/c || \
> mkdir -p tmp/a/b/c && \
> tar xvf -C tmp/a/b/c ~/archive.tar

Alternatively, the following configuration also works:

Listing 10. Alternative example of good habit #5: Using a backslash for long input

~ $ cd tmp/a/b/c \
> || \
> mkdir -p tmp/a/b/c \
> && \
> tar xvf -C tmp/a/b/c ~/archive.tar

However you divide an input line over multiple lines, the shell always treats it as one continuous line, because it always strips out all the backslashes and extra spaces.

Note: In most shells, when you press the up arrow key, the entire multi-line entry is redrawn on a single, long input line.

Group your commands together in a list

Most shells have ways to group a set of commands together in a list so that you can pass their sum-total output down a pipeline or otherwise redirect any or all of its streams to the same place. You can generally do this by running a list of commands in a subshell or by running a list of commands in the current shell.

Run a list of commands in a subshell

Use parentheses to enclose a list of commands in a single group. Doing so runs the commands in a new subshell and allows you to redirect or otherwise collect the output of the whole, as in the following example:

Listing 11. Example of good habit #6: Running a list of commands in a subshell

~ $ ( cd tmp/a/b/c/ || mkdir -p tmp/a/b/c && \
> VAR=$PWD; cd ~; tar xvf -C $VAR archive.tar ) \
> | mailx admin -S “Archive contents”

In this example, the content of the archive is extracted in the tmp/a/b/c/ directory while the output of the grouped commands, including a list of extracted files, is mailed to the admin address.

The use of a subshell is preferable in cases when you are redefining environment variables in your list of commands and you do not want those definitions to apply to your current shell.

Run a list of commands in the current shell

Use curly braces ({}) to enclose a list of commands to run in the current shell. Make sure you include spaces between the braces and the actual commands, or the shell might not interpret the braces correctly. Also, make sure that the final command in your list ends with a semicolon, as in the following example:

Listing 12. Another example of good habit #6: Running a list of commands in the current shell

~ $ { cp ${VAR}a . && chown -R guest.guest a && \
> tar cvf newarchive.tar a; } | mailx admin -S “New archive”

Use xargs outside of find

Use the xargs tool as a filter for making good use of output culled from the find command. The general precept is that a find run provides a list of files that match some criteria. This list is passed on to xargs, which then runs some other useful command with that list of files as arguments, as in the following example:

Listing 13. Example of the classic use of the xargs tool

~ $ find some-file-criteria some-file-path | \
> xargs some-great-command-that-needs-filename-arguments

However, do not think of xargs as just a helper for find; it is one of those underutilized tools that, when you get into the habit of using it, you want to try on everything, including the following uses.

Passing a space-delimited list

In its simplest invocation, xargs is like a filter that takes as input a list (with each member on a single line). The tool puts those members on a single space-delimited line:

Listing 14. Example of output from the xargs tool

~ $ xargs
a
b
c
Control-D
a b c
~ $

You can send the output of any tool that outputs file names through xargs to get a list of arguments for some other tool that takes file names as an argument, as in the following example:

Listing 15. Example of using of the xargs tool

~/tmp $ ls -1 | xargs
December_Report.pdf README a archive.tar mkdirhier.sh
~/tmp $ ls -1 | xargs file
December_Report.pdf: PDF document, version 1.3
README: ASCII text
a: directory
archive.tar: POSIX tar archive
mkdirhier.sh: Bourne shell script text executable
~/tmp $

The xargs command is useful for more than passing file names. Use it any time you need to filter text into a single line:

Listing 16. Example of good habit #7: Using the xargs tool to filter text into a single line

~/tmp $ ls -l | xargs
-rw-r–r– 7 joe joe 12043 Jan 27 20:36 December_Report.pdf -rw-r–r– 1 \
root root 238 Dec 03 08:19 README drwxr-xr-x 38 joe joe 354082 Nov 02 \
16:07 a -rw-r–r– 3 joe joe 5096 Dec 14 14:26 archive.tar -rwxr-xr-x 1 \
joe joe 3239 Sep 30 12:40 mkdirhier.sh
~/tmp $

Be cautious using xargs

Technically, a rare situation occurs in which you could get into trouble using xargs. By default, the end-of-file string is an underscore (_); if that character is sent as a single input argument, everything after it is ignored. As a precaution against this, use the -e flag, which, without arguments, turns off the end-of-file string completely.

Know when grep should do the counting — and when it should step aside

Avoid piping a grep to wc -l in order to count the number of lines of output. The -c option to grep gives a count of lines that match the specified pattern and is generally faster than a pipe to wc, as in the following example:

Listing 17. Example of good habit #8: Counting lines with and without grep

~ $ time grep and tmp/a/longfile.txt | wc -l
2811

real 0m0.097s
user 0m0.006s
sys 0m0.032s
~ $ time grep -c and tmp/a/longfile.txt
2811

real 0m0.013s
user 0m0.006s
sys 0m0.005s
~ $

An addition to the speed factor, the -c option is also a better way to do the counting. With multiple files, grep with the -c option returns a separate count for each file, one on each line, whereas a pipe to wc gives a total count for all files combined.

However, regardless of speed considerations, this example showcases another common error to avoid. These counting methods only give counts of the number of lines containing matched patterns — and if that is what you are looking for, that is great. But in cases where lines can have multiple instances of a particular pattern, these methods do not give you a true count of the actual number of instances matched. To count the number of instances, use wc to count, after all. First, run a grep command with the -o option, if your version supports it. This option outputs only the matched pattern, one on each line, and not the line itself. But you cannot use it in conjunction with the -c option, so use wc -l to count the lines, as in the following example:

Listing 18. Example of good habit #8: Counting pattern instances with grep

~ $ grep -o and tmp/a/longfile.txt | wc -l
3402
~ $

In this case, a call to wc is slightly faster than a second call to grep with a dummy pattern put in to match and count each line (such as grep -c).

Match certain fields in output, not just lines

A tool like awk is preferable to grep when you want to match the pattern in only a specific field in the lines of output and not just anywhere in the lines.

The following simplified example shows how to list only those files modified in December:

Listing 19. Example of bad habit #9: Using grep to find patterns in specific fields

~/tmp $ ls -l /tmp/a/b/c | grep Dec
-rw-r–r– 7 joe joe 12043 Jan 27 20:36 December_Report.pdf
-rw-r–r– 1 root root 238 Dec 03 08:19 README
-rw-r–r– 3 joe joe 5096 Dec 14 14:26 archive.tar
~/tmp $

In this example, grep filters the lines, outputting all files with Dec in their modification dates as well as in their names. Therefore, a file such as December_Report.pdf is matched, even if it has not been modified since January. This probably is not what you want. To match a pattern in a particular field, it is better to use awk, where a relational operator matches the exact field, as in the following example:

Listing 20. Example of good habit #9: Using awk to find patterns in specific fields

~/tmp $ ls -l | awk ‘$6 == “Dec”‘
-rw-r–r– 3 joe joe 5096 Dec 14 14:26 archive.tar
-rw-r–r– 1 root root 238 Dec 03 08:19 README
~/tmp $


Stop piping cats

A basic-but-common grep usage error involves piping the output of cat to grep to search the contents of a single file. This is absolutely unnecessary and a waste of time, because tools such as grep take file names as arguments. You simply do not need to use cat in this situation at all, as in the following example:

Listing 21. Example of good and bad habit #10: Using grep with and without cat

~ $ time cat tmp/a/longfile.txt | grep and
2811

real 0m0.015s
user 0m0.003s
sys 0m0.013s
~ $ time grep and tmp/a/longfile.txt
2811

real 0m0.010s
user 0m0.006s
sys 0m0.004s
~ $

This mistake applies to many tools. Because most tools take standard input as an argument using a hyphen (-), even the argument for using cat to intersperse multiple files with stdin is often not valid. It is really only necessary to concatenate first before a pipe when you use cat with one of its several filtering options.

Source: ibm.com

Popularity: 24% [?]

Basic Apache and PHP Install from Source Part 1

Ok, I may not be a guru when it comes to installing and configuring Apache and PHP but here is a sample of how I install Apache and PHP on Fedora or Red Hat boxes fresh from source. Pardon my newbie-sh technique but here it goes:

Installing Apache:

# cd /usr/src

- Download the http package

# wget http://www.apache.org/dist/httpd/httpd-2.2.8.tar.gz (change this to a mirror available to you)

- Extract the contents of the package

# tar zxf httpd-2.2.8.tar.gz

# cd httpd-2.2.8

- Configure the source depending on your requirements. At this point, configure may fail because of unsatisfied dependencies. Check what the error is and you can download the required package using yum or up2date. If you do not need SSL module for secure page (https), you can leave out the –enable-ssl part.

# ./configure –prefix=/usr/local/apache –with-mpm=prefork –enable-ssl –with-ssl=/usr/local/ssl –enable-log_config=static –enable-vhost_alias=static –enable-includes=static –enable-dir=static –enable-access=static –enable-mime=static –enable-mime_magic=static –enable-mods-shared=most –enable-cache=shared –enable-disk_cache=shared –enable-file_cache=shared –enable-mem_cache=shared

Tip: To check what these directives mean, you can issue ./configure –help .

# make

- If everything goes well, your fresh http will be installed in /usr/local/apache with the following command:

# make install

Installing PHP:

# cd /usr/src

# wget http://www.php.net/get/php-5.2.5.tar.gz/from/us.php.net/mirror (change this to a mirror available to you)

# tar zxf php-5.2.5.tar.gz

# cd php-5.2.5

- Same with http. The configure part will depend on your requirement.

# ./configure –with-config-file-path=/usr/local/apache/conf –with-apxs2=/usr/local/apache/bin/apxs –enable-calendar –enable-ftp –without-pgsql –with-zlib –with-openssl=/usr/local/ssl –with-mysql –with-mhash –with-mcrypt –with-curl –disable-cgi –enable-mbstring –enable-soap –with-bz2 –enable-sockets –enable-zip (If configure fails, read the error why the it failed and install first the dependencies then run again the configure.)

# make

# make test

# make install

To start the httpd service, execute

# /usr/local/apache/bin/apachectl start

You can create a symlink to your /etc/init.d so you can start apache by typing /etc/init.d/httpd start

# ln -s /usr/local/apache/bin/apachectl /etc/init.d/httpd

There you have it. You have successfully installed Apache with PHP on your webserver. I will continue this little howto with how to configure your webserver.

Popularity: 12% [?]

Ultimate Linux Cheat Sheets

If you are in dire need of SOS because of that little command that is stuck at the tip of your tongue or you are having a huge case of memory gap, fret not. Here is a quick link to a massive list of Unix/Linux cheat sheets. One link points to http://www.tuxfiles.org/linuxhelp/linuxcommands.html which profiles a list of Linux commands that are newbie friendly.

List too long for you? You can try the Linux command apropos <keyword>. This command searches the whatis database for strings that matches your keyword. Let’s say you forgot the command to copy a file (uh-oh) so we go like this:

# apropos copy

# cp (1) - copy files and directories
# cp (1p) - copy files

Hey there it is! ;) So we got cp. You can now use man command to check if cp is really what you are looking for. Google is also a neat tool if internet access is readily available. :D

Popularity: 10% [?]

Save Your Files With FlyBack

Still looking for a backup program for your Linux files? Finally, FlyBack is available to Linux users to backup our stuff and save our a$$es from humiliating and headache-producing data loss.

FlyBack is a snapshot-based backup tool based on rsync It creates successive backup directories mirroring the files you wish to backup, but hard-links unchanged files to the previous backup. This prevents wasting disk space while providing you with full access to all your files without any sort of recovery program. If your machine crashes, just move your external drive to your new machine and copy the latest backup using whatever file browser you normally use.

Bernaz’s Weblog writes about FlyBack and you can continue reading here.

Popularity: 23% [?]

Howto: Install yum On RHEL 4

There are more than a couple of ways of updating Red Hat Enterprise Linux (RHEL) packages on your machine. One is by using up2date, the default package updater of RHEL systems. Unlike Fedora and CentOS which uses yum, up2date requires you to be registered to Red Hat Network (RHN) to be able to download or update your packages from the RHN repository.

Now, what if you need to install a certain package that is not available in your current repository by up2date? Or what if the package in the repository wreaks havoc in your system? Maybe you should try using yum to install or update rpm packages.

But… but… but how can I install yum in my RHEL machine?, you may ask. It’s actually very simple.

I got this tip from Babar Haq’s Blog with a little modification since I am using RHEL 4.

1. Download yum by using wget

# wget http://linux.duke.edu/projects/yum/download/2.0/yum-2.0.8-1.noarch.rpm

2. Install the rpm

# rpm -ivh yum-2.0.8-1.noarch.rpm

3. Configure /etc/yum.conf to use compatible repository

[main]
cachedir=/var/cache/yum
debuglevel=2
logfile=/var/log/yum.log
pkgpolicy=newest
distroverpkg=redhat-release
tolerant=1
exactarch=1

[base]
name=CentOS-$releasever - Base
baseurl=http://mirror.centos.org/centos/4/os/i386/
gpgcheck=1

[updates]
name=Red Hat Linux $releasever - Updates
baseurl=http://mirror.centos.org/centos/4/updates/i386/
gpgcheck=1

4. Download and install the CentOS GPG Key

# wget http://mirror.centos.org/centos/RPM-GPG-KEY-CentOS-4

# rpm –import RPM-GPG-KEY-CentOS-4

5. Test yum to see if it works (I tested by running full update on my machine)

# yum update

*Note: This will update ALL installed packages in your machine. If you do not want to do this, cancel the process or skip this step.

If you reach step 5 without encountering any errors, it means that yum is successfully updating your machine with the latest versions available in the repo. :-h

This worked perfectly fine for me. If you experienced any errors, post a message and I will try to help you out ;)

Popularity: 37% [?]

Setting Up Remote Connection Using FreeNX

Want to remote access your Linux desktop? Or access your workstation similar the way Remote Desktop does it?

While Linux offers a wide array of ways to connect to a remote computer, some people still prefer to connect the traditional way by using ssh. Not only it is secure, it is sure is a fast way of connecting a remote terminal. However, if you want to remotely access your Linux desktop, freeNX can do the job along with NoMachine client.

What is freeNX?

From the official website:

NX is an exciting new technology for remote display. It provides near local speed application responsiveness over high latency, low bandwidth links. The core libraries for NX are provided by NoMachine under the GPL. FreeNX is a GPL implementation of the NX Server.

Linux is to freeNX as Windows is to Remote Desktop. I decided to use freeNX to access my Linux desktop in office if ever I need to.

Setting up freeNx:

freeNX is available for download in source tarballs and distribution packages.I personally use the distribution package for Fedora/Redhat which is available via yum. I am using Fedora 7 so in this case, I will use the steps of setting up freeNX for my distro.

# Make sure you are up-to-date
yum update

# Install FreeNX and all dependencies
yum install freenx

#SERVER SETUP IS DONE! The RPM takes care of the required setup.

That’s it! However, if you are using Fedora versions older than Fedora 5, there is a special how-to for freeNX setup that you might want to check.

Install NoMachine client:

Remote connection also needs a client which is the program you use that connects to your remote server, in this case the freeNX server. In this tutorial, we will be using NoMachine as the client. You can download the NoMachine client here. In my example, I will be using Windows XP for my workstation client so I have to download and install the NoMachine client for Windows. Install the client and run the NX Client for Windows. This will open up a dialog box for your client configuration. Here are the steps you need to setup your client:

  •  When the dialog box opens, enter the Session and Host name for your connection. Session name is the name of your connection and your settings will be saved under this name. Host name is the ip address or hostname and port of the remote machine. The default port is 22 (SSH). Click Next.
  • In the next dialog box, select Unix and choose which type of window manager you want to use and the resolution. In this case I user KDE and Available Area for my resolution. Check the box for Enable SSL encryption. Click Next.
  • If you want to put a shortcut to this connection on your desktop, put a tick on the Create shortcut on desktop checkbox and click Finish.

If you want to open the session, double click the shortcut on your Desktop and type in your username and password for this session. You will be connecting now to your freeNX server and you will see your Available sessions box. Select New to create a new session to begin connecting to your remote desktop. Wait for the desktop to load and voila! You are now connected to your remote desktop.

Popularity: 12% [?]

Partitioning Disks with fdisk

Every computer owner will come across the street road called Partitioning. Partitioning simply means dividing your physical hard drive into 2 or more logical (or virtual) drives. In Linux there are different kinds of applications that can help you do this, and one is fdisk.

For this example, I will demonstrate how to use fdisk.

The basic command goes like fdisk <device-name> like:

# fdisk /dev/hda

The number of cylinders for this disk is set to 14596.
There is nothing wrong with that, but this is larger than 1024,
and could in certain setups cause problems with:
1) software that runs at boot time (e.g., old versions of LILO)
2) booting and partitioning software from other OSs
(e.g., DOS FDISK, OS/2 FDISK)

Command (m for help):

To display the help menu or if you want to list all of available commands:

Command (m for help): m
Command action
a toggle a bootable flag
b edit bsd disklabel
c toggle the dos compatibility flag
d delete a partition
l list known partition types
m print this menu
n add a new partition
o create a new empty DOS partition table
p print the partition table
q quit without saving changes
s create a new empty Sun disklabel
t change a partition’s system id
u change display/entry units
v verify the partition table
w write table to disk and exit
x extra functionality (experts only)

Now for the action. Let’s say we need to see how many partitions are in the disk.

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120060444672 bytes
255 heads, 63 sectors/track, 14596 cylinders, total 234493056 sectors
Units = sectors of 1 * 512 = 512 bytes

Device Boot Start End Blocks Id System
/dev/hda1 * 63 30716279 15358108+ 83 Linux
/dev/hda2 30716280 81915434 25599577+ 83 Linux
/dev/hda3 81915435 82975724 530145 82 Linux swap / Solaris
/dev/hda4 82975725 234484739 75754507+ 5 Extended
/dev/hda5 82975788 234484739 75754476 83 Linux

So there are 4 primary partitions - hda1, hda2, hda3 and hda4. The last partition, hda4, is the Extended Partition or the Logical Partition which contains the hda5 partition.

Now that we have seen all the partitions, let us say that we are going to delete the /dev/hda1partition and create a new one.

But before we can create a new one, we should delete the old one first. These steps does not execute the commands at once. If you made a mistake, you can just quit the program without committing any changes.

To delete a partition, just type d on the prompt. For this example, what I want to do is delete the first partition, /dev/hda1:

Command (m for help): d
Partition number (1-5): 1

The partition number means that /dev/hda1will be deleted. To check if we have typed in the correct partition number (I hope I did!) just do:

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120060444672 bytes
255 heads, 63 sectors/track, 14596 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/hda2 1913 5099 25599577+ 83 Linux
/dev/hda3 5100 5165 530145 82 Linux swap / Solaris
/dev/hda4 5166 14596 75754507+ 5 Extended
/dev/hda5 5166 14596 75754476 83 Linux

Voila! /dev/hda1 is no longer there. But no worries, it is still there. We just need to create a new one.

Command (m for help): n
Command action
l logical (5 or over)
p primary partition (1-4)
p
Selected partition 1
First cylinder (1-14596, default 1):
Using default value 1
Last cylinder or +size or +sizeM or +sizeK (1-1912, default 1912):
Using default value 1912

Command (m for help): p

Disk /dev/hda: 120.0 GB, 120060444672 bytes
255 heads, 63 sectors/track, 14596 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes

Device Boot Start End Blocks Id System
/dev/hda1 1 1912 15358108+ 83 Linux
/dev/hda2 1913 5099 25599577+ 83 Linux
/dev/hda3 5100 5165 530145 82 Linux swap / Solaris
/dev/hda4 5166 14596 75754507+ 5 Extended
/dev/hda5 5166 14596 75754476 83 Linux

The n command will create a new partition, in this case, replacing the old /dev/hda1 that we have deleted and the p command will display that we have successfully created a new one (yay!).

To commit the changes, type w on the prompt.

Command (m for help): m
Command action
w write table to disk and exit

But for now we will exit fdisk without saving the changes.

Command (m for help): q

That’s all for fdisk for now. There are other commands available on fdisk, just do not forget the use the man pages and the m command. If you have deleted a big chunk of important files, well, experience is the best teacher ;)

Popularity: 8% [?]