AirV's Blog

Just another blog

Expressions régulières

From HowToGeek :

What are Regular Expressions?

Regular expressions are statements formatted in a very specific way and that can stand for many different results. Also known as “regex” or “regexp,” they are primarily used in search and file naming functions. One regex can be used like a formula to create a number of different possible outputs, all of which are searched for. Alternatively, you can specify how a group of files should be named by specifying a regex, and your software can incrementally move to the next intended output. This way, you can rename multiple files in multiple folders very easily and efficiently, and you can move beyond the limitations of a simple numbering system.

Because the use of regular expressions relies on a special syntax, your program must be capable of reading and parsing them. Many batch file renaming programs for Windows and OS X have support for regexps, as well as the cross-platform searching tool GREP (which we touched on in our Bash Scripting for Beginners Guide) and the Awk command-line tool for *Nix. In addition, many alternative file managers, launchers, and searching tools use them, and they have a very important place in programming languages like Perl and Ruby. Other development environments like .NET, Java, and Python, as well as the upcoming C++ 11, all provide standard libraries for using regular expressions. As you can imagine, they can be really useful when trying to minimize the amount of code you put into a program.

A Note About Escaping Characters

Before we show you with examples, we’d like to point something out. We’re going to be using the bash shell and the grep command to show you how to apply regular expressions. The problem is that sometimes we want to use special characters that need to be passed to grep, and the bash shell will interpret that character because the shell uses it as well. In these circumstances, we need to “escape” these characters. This can get confusing because this “escaping” of characters also occurs inside regexps. For example, if we want to enter this into grep:

<

we’ll have to replace that with:

\<

Each special character here gets one backslash. Alternatively, you can also use single quotes:

‘<’

Single quotes tell bash NOT to interpret what’s inside of them. While we require these steps to be taken so we can demonstrate for you, your programs (especially GUI-based ones) often won’t require these extra steps. To keep things simple and straightforward, the actual regular expression will be given to you as quoted text, and you’ll see the escaped syntax in the command-line screenshots.

How Do They Expand?

Regexps are a really concise way of stating terms so that your computer can expand them into multiple options. Let’s take a look at the following example:

tom[0123456789]

The square brackets – [ and ] – tell the parsing engine that whatever is inside, any ONE character may be used to match. Whatever is inside those brackets is called a character set.

So, if we had a huge list of entries and we used this regex to search, the following terms would be matched:

  • tom
  • tom0
  • tom1
  • tom2
  • tom3

and so on. However, the following list would NOT be matched, and so would NOT show up in your results:

  • tomato ; the regex does not account for any letters after “tom”
  • Tom ; the regex is case sensitive!

You can also choose to search with a period (.) which will allow any character present, as long as there is a character present.

reg vs period

As you can see, grepping with

.tom

did not bring up terms that only had “tom” at the beginning. Even “green tomatoes” came in, because the space before “tom” counts as a character, but terms like “tomF” did not have a character at the beginning and were thus ignored.

Note: Grep’s default behavior is to return a whole line of text when some part matches your regex. Other programs may not do this, and you can turn this off in grep with the ‘-o’ flag.

You can also specify alternation using a pipe (|), like here:

speciali(s|z)e

This will find both:

  • specialise
  • specialize

When using the grep command, we need to escape the special characters (, |, and ) with backslashes as well as utilize the ‘-E’ flag to get this to work and avoid ugly errors.

escape paren pipe

As we mentioned above, this is because we need to tell the bash shell to pass these characters to grep and not to do anything with them. The ‘-E’ flag tells grep to use the parentheses and pipe as special characters.

You can search by exclusion using a caret that is both inside of your square brackets and at the beginning of a set:

tom[^F|0-9]

Again, if you’re using grep and bash, remember to escape that pipe!

caret

Terms that were in the list but did NOT show up are:

  • tom0
  • tom5
  • tom9
  • tomF

These did not match our regex.

How Can I Utilize Environments?

Often, we search based on boundaries. Sometimes we only want strings that appear at the beginning of a word, at the end of a word, or at the end of a line of code. This is can be easily done using what we call anchors.

Using a caret (outside of brackets) allows you to designate the “beginning” of a line.

^tom

beg of line

To search for the end of a line, use the dollar sign.

tom$

end of line

You can see that our search string comes BEFORE the anchor in this case.

You can also for matches that appear at the beginning or end of words, not whole lines.

<tom

tom>

beg of word

end of word

As we mentioned in the note at the beginning of this article, we need to escape these special characters because we’re using bash. Alternatively, you can also use single quotes:

beg of word q

end of word q

The results are the same. Make sure you use single quotes, and not double quotes.

Other Resources For Advanced Regexps

We’ve only hit the tip of the iceberg here. You can also search for money terms delineated by the currency marker, and search for any of three or more matching terms. Things can get really complicated. If you’re interested in learning more about regular expressions, then please take a look at the following sources.

  • Zytrax.com has a few pages with specific examples of why things do and do not match.
  • Regular-Expressions.info also has a killer guide to a lot of the more advanced stuff, as well as a handy reference page.
  • Gnu.org has a page dedicated to using regexps with grep.

You can also build and test out your regular expressions using a free Flash-based online tool called RegExr. It works as you type, is free, and can be used in most browsers.

Ubuntu Unity

From http://www.tux-planet.fr, article publié le 28 Avril 2011

Depuis la sortie d’Ubuntu 11.04, on peut utiliser une nouvelle interface de bureau appelée Unity. Cette page regroupe les principales astuces d’utilisation de ce nouveau système.

 

Sommaire

Comment configurer Unity ?

Configuration d'Unity

De base, il n’y a pas vraiment d’outils pour configurer l’interface d’Unity. Un plugin pour le gestionnaire de configuration Compiz a quand même été développé et voici les commandes à utiliser pour l’installer et le lancer :

sudo apt-get install compizconfig-settings-manager
ccsm

Recherchez ensuite « Unity » dans le champ de filtrage pour accéder au panneau de configuration. Vous pourrez par exemple changer l’emplacement du lanceur d’applications (le mettre en bas, à droite), modifier la taille des icônes, ou effectuer d’autres paramétrages…

Les différents raccourcis clavier

L’interface Unity s’utilise énormément au clavier et l’apprentissage de quelques raccourcis est donc une phase quasi-obligatoire. A noter que la touche Super correspond à la touche Windows de votre clavier.

Le lanceur d’applications

    • Super – Afficher le lanceur d’applications
    • Super (maintenir la touche) puis touches 1, 2, 3… Sélectionner une application dans la barre de lancement

Unity

  • Super + T – Ouvrir la corbeille
  • Alt + F1 – Positionner le clavier sur le premier icône du lanceur d’applications
  • Alt + F2 – Lancer une commande
  • Super + A – Faire une recherche parmi les applications
  • Super + F – Faire une recherche de fichiers
  • Ctrl + Alt + T : Ouvrir un terminal

Le menu

  • F10 – Ouvrir le premier menu. On peut ensuite utiliser les flèches de direction pour accéder aux menus suivants.

La gestion des fenêtres

  • Super + W – Zoomer en arrière sur toutes les fenêtres de tous les bureaux
  • Super + D – Agrandir ou réduire toutes les fenêtres
  • Alt + F10 – Agrandir ou réduire la fenêtre courante
  • Alt + F9 – Réduire la fenêtre courante
  • Alt + Tab – Naviguer parmi les fenêtres ouvertes
  • Alt + F4 – Fermer la fenêtre courante

Le déplacement de fenêtres

  • Ctrl + Alt + Numpad 7 – Déplacer la fenêtre dans le coin supérieur gauche de l’écran
  • Ctrl + Alt + Numpad 8 – Déplacer la fenêtre en haut au milieu de l’écran
  • Ctrl + Alt + Numpad 9 – Déplacer la fenêtre dans le coin supérieur droit de l’écran
  • Ctrl + Alt + Numpad 4 – Déplacer la fenêtre dans le coin gauche au milieu de l’écran
  • Ctrl + Alt + Numpad 5 – Centrer ou Agrandir la fenêtre au lieu de l’écran
  • Ctrl + Alt + Numpad 6 – Déplacer la fenêtre dans le coin droit au milieu de l’écran
  • Ctrl + Alt + Numpad 1 – Déplacer la fenêtre dans le coin inférieur gauche de l’écran
  • Ctrl + Alt + Numpad 2 – Déplacer la fenêtre dans le coin inférieur au mileu de l’écran
  • Ctrl + Alt + Numpad 3 – Déplacer la fenêtre dans le coin inférieur droit de l’écran
  • Ctrl + Alt + Numpad 0 – Agrandir la fenêtre

On remarquera que si l’on utilise plusieurs fois la touche avec le chiffre, on obtient des redimensionnements différents.

La gestion de bureaux

  • Super + S – Expo Mode : Zoomer en arrière sur tous les bureaux et déplacer des fenêtres
  • Shift + Alt + ↑ – Expo Mode mais uniquement pour le bureau actif
  • Ctrl + Alt + ← / → / ↑ / ↓ – Changer de bureau
  • Ctrl + Alt + Shift + ← / → / ↑ / ↓ – Déplacer la fenêtre active vers un autre bureau

Screenshots

  • Print – Faire une capture d’écran du bureau
  • Alt + Print – Faire une capture d’écran de la fenêtre active

Autres astuces pour Unity

    • Dans le lanceur d’applications, on peut faire du drag and drop sur les icônes afin de réorganiser leurs positionnements.
    • Pour ajouter une icône au lanceur, il suffit de rechercher l’application (utilisez les touches Super + A) et de glisser ensuite l’icône ver la barre de lancement.
    • Si l’on déplace l’icône dans la corbeille, celle-ci est supprimée.
    • Un clic roulette sur une icône du lanceur permet d’ouvrir l’application dans une nouvelle fenêtre.
    • Si l’on déplace une fenêtre tout en haut de l’écran, celle-ci est automatiquement agrandie. L’effet inverse est également valable pour réduire la taille d’une fenêtre
    • Un clic droit sur une icône du lanceur permet d’ouvrir un menu proposant de nouvelles options

Unity

  • Lorsque l’on utilise la roulette de la souris sur l’icône de volume, on peut ajuster le volume sonore (valable pour l’interface Gnome classique également).

Comment réinitialiser les paramètres d’Unity ?

Pour remettre les paramètres d’Unity par défaut, ouvrez un terminal et lancez les commandes suivantes :

gsettings reset com.canonical.Unity.Launcher favorites
unity –reset

Et si on veut réinitialiser les icônes du lanceur :

unity –reset-icons

Comment agrandir la fenêtre du Dash Overlay ?

Lorsque l’on fait une recherche d’applications ou de fichiers avec Unity, une fenêtre noire appelée « Dash Overlay » apparaît. Par défaut, celle-ci occupe une petite partie de l’écran. Voici une astuce pour faire en sorte que toute la surface soit utilisée.

Lancez la commande suivante pour agrandir la fenêtre et occuper toute la surface de l’écran :

gsettings set com.canonical.Unity form-factor ‘Netbook’

Ou l’une des deux commandes suivantes pour revenir en mode normal :

gsettings set com.canonical.Unity form-factor ‘Automatic’
gsettings set com.canonical.Unity form-factor ‘Desktop’

Comment installer et utiliser Unity 2D pour les ordinateurs peu puissants ?

Si votre ordinateur n’est pas assez puissant pour lancer Unity, sachez qu’il existe une version 2D beaucoup plus légère.

Unity 2D

Pour l’installer, ouvrez un terminal et lancez les commandes suivantes :

sudo add-apt-repository ppa:unity-2d-team/unity-2d-daily
sudo apt-get update
sudo apt-get install unity-2d

Ensuite, déconnectez-vous et ouvrez une nouvelle session en choisissant « Unity 2D » comme environnement de travail.

Comment ajouter un accès rapide au répertoire Téléchargements, Images, Documents, Vidéos… ?

Avec Unity, il est possible d’améliorer les menus contextuelles des applications. Voici comment ajouter des accès rapides à certains répertoires lorsque l’on fait un clic droit sur l’icône de gestion de fichiers.

Home Folder Quicklist

Ouvrez un terminal et lancer ce qui suit en une seule commande :

echo « [Desktop Entry]

Name=Home Folder
Comment=Open your personal folder
TryExec=nautilus
Exec=nautilus –no-desktop
Icon=user-home
Terminal=false
StartupNotify=true
Type=Application
Categories=GNOME;GTK;Core;
OnlyShowIn=GNOME;Unity;
X-GNOME-Bugzilla-Bugzilla=GNOME
X-GNOME-Bugzilla-Product=nautilus
X-GNOME-Bugzilla-Component=general
X-Ubuntu-Gettext-Domain=nautilus

X-Ayatana-Desktop-Shortcuts=Videos;Documents;Music;Pictures;Downloads
[Videos Shortcut Group]
Name=Videos
Exec=nautilus Videos
TargetEnvironment=Unity

[Documents Shortcut Group]
Name=Documents
Exec=nautilus Documents
TargetEnvironment=Unity

[Music Shortcut Group]
Name=Music
Exec=nautilus Music
TargetEnvironment=Unity

[Pictures Shortcut Group]
Name=Pictures
Exec=nautilus Pictures
TargetEnvironment=Unity

[Downloads Shortcut Group]
Name=Downloads
Exec=nautilus Downloads
TargetEnvironment=Unity » | sudo tee /usr/share/applications/nautilus-home.desktop

Si la modification n’est pas prise en compte aussitôt, il faudra peut-être ré-ouvrir votre session Unity.

Comment désactiver GlobalMenu ?

Si vous n’aimez pas le menu global, voici la commande à utiliser pour le désactiver :

sudo apt-get remove appmenu-gtk indicator-applet-appmenu indicator-appmenu

Comment cacher les icônes des périphériques dans la barre de lancement ?

Lorsque l’on branche un périphérique externe ou que l’on fait un montage, une nouvelle icône apparaît dans la barre de lancement des applications.

Montage des périphériques

Voici la commande à utiliser pour les cacher de façon définitive :

gsettings set com.canonical.Unity.Devices devices-option « Never »

Comment désactiver Unity ?

Tout le monde n’aime pas forcément Unity, voici donc deux astuces pour désactiver ce système. La première méthode consiste tout simplement à sélectionner une session « Gnome classique » au moment de rentrer son login / mot de passe.

Désactiver Unity

La seconde méthode, plus radicale, consiste à désinstaller Unity avec la commande suivante :

sudo apt-get –purge remove unity && sudo apt-get –purge autoremove

Comment modifer le menu ouvrir avec ?

Il faut modifier le ficher /usr/share/applications/default.list

Vinagre

Vinagre est un afficheur de bureaux à distance (vnc, ssh) intégré au bureau Gnome. Avec Vinagre vous pouvez avoir plusieurs connexions ouvertes simultanément, créer des signets de vos serveurs grâce au support des favoris, mémoriser les mots de passe dans le trousseau de clefs de GNOME, et parcourir le réseau à la recherche de serveurs VNC.

 

 

Ubuntu look like Windows Seven

From HowToGeek :

Installing the Win7 Theme

sudo wget http://web.lib.sun.ac.za/ubuntu/files/help/theme/gnome/win7-setup.sh

sudo chmod 0755 ~/win7-setup.sh

~/win7-setup.sh

 

History

commande history

  • Liste des dernières commandes

history

  • Exécution de la commande 550

!550

  • Dernière commande

!!

  • Commande cd avec le dernier argument passé

cd !$

  • Recherche d’une occurrence :

Ctrl R puis saisir l’occurrence

!Occurence

 

Pour plus d’informations voir HowToGeek.com

Serveur Ubuntu

Zentyal propose une solution de serveur Ubuntu offrant une palette impressionnante de services :

  • DHPCP, DNS, WEB , FTP…
  • LDAP, Calendrier, Partage de fichiers, Backup…
  • Messsagerie, VoIP…
  • Firewall, VPN…

Ndiswrapper

How to Install a Wireless Card in Linux Using Windows Drivers

From HowToGeek.com :


Linux has come a long way with hardware support, but if you have a wireless card that still does not have native Linux drivers you might be able to get the card working with a Windows driver and ndiswrapper.

Using a Windows driver inside of Linux may also give you faster transfer rates or better encryption support depending on your wireless card.

If your wireless card is working, it is not recommended to install the Windows driver just for fun because it could cause a conflict with the native Linux driver.

Download Wireless Card Driver

The first thing you need to do is figure out what wireless card you have. There are a couple ways to do this and some involve finding the device chipset and others involve scouring through system logs.

The easiest method is to just look at the device itself, if you have an external wireless card, or search your manufactures website for what wireless card came with your computer, if you have an internal wireless card.

Once you know what wireless adapter you are trying to install, go to the manufacturer’s website to download the Windows drivers for the device.

If at all possible, you should try to download the 32-bit Windows XP drivers in .zip format rather than .exe. If you don’t have an option, select the latest Windows driver that your manufacturer provides.

Extract Wireless Driver

To extract the files, browse to the .exe or .zip file, right click on it, and select open with archive manager.

Note: Although archive manager can extract both .exe and .zip files, sometimes the files within the .exe may not work with ndiswrapper.

Click extract at the top and copy all the files to an easy to find location.

Install Ndiswrapper

Ndiswrapper is the tool that allows Linux to use Windows drivers for wireless card support.

To install it in Ubuntu go to the Software Center and search for ndisgtk.

Note: Linux Mint comes with ndiswrapper installed.

Install Windows Driver

Now that you have your wireless driver extracted and ndiswrapper installed, open Windows Wireless Drivers from the System -> Administration menu.

In the window that opens, click on install new driver and browse to where you extracted the driver.

Sometimes the .inf files will be in sub-folders inside the driver so you may need to dig around to locate the right file to use.

After you select the .inf file for your wireless card click install. It will take a couple minutes to install the driver so be patient while it works.

After the driver is installed the main window will indicate if you selected the right .inf file by telling you if the hardware is present or not. If you selected the wrong driver the first time you can try installing a different .inf file that was extracted from the driver.

If none of the .inf files work you may want to try the driver for the same card for a different version of Windows (e.g. XP, Vista, 7).

After you get the right driver installed click configure network to open Ubuntu network connections and connect to your wireless network.

If you are still having trouble you may want to check out the ndiswrapper wiki to see if others have had success with the wireless card.

GRUB2

From HowToGeek.com :

Installing Grub Customizer

The tool in question is called Grub Customizer, created by Daniel Richter. He’s provided a PPA to make installing the tool quick and easy.

Open a terminal window (Ctrl+Alt+T or Applications > Accessories > Terminal) and type in the following commands.

sudo add-apt-repository ppa:danielrichter2007/grub-customizer
sudo apt-get update
sudo apt-get install grub-customizer

Grub Customizer will now show up in the Applications > System Tools menu.

sshot-1

Or you can open it from the command line.

gksudo grub-customizer

Hide Boot Menu Options

Over time, your boot menu can get cluttered with old versions of the Linux kernel. In a previous article, we showed you how to remove these manually; Grub Customizer makes this process much easier.

When Grub Customizer starts up, you’ll see a list of all the items that show up in the boot menu.

Grub Customizer_002

To hide entries that you don’t want to see anymore, simply uncheck the checkbox next to them.

Grub Customizer_004

Click the Save button at the top-left to make your changes permanent.

sshot-3

You can uncheck entire sections if you don’t want Grub2 to probe for new operating systems, or give you the option to test your computer’s memory.

Note that, unlike the manual method, this process does not actually remove the kernels from your computer, it just hides them from the boot menu.

Customize Grub Behavior

Grub Customizer can do much more than hide boot menu entries! Opening up the Preferences window lets you customize almost every aspect of Grub.

For example, you can set the default boot menu entry to a certain position, or a specific item.

sshot-2

If you’re bored by the default white-text-on-black-background look of Grub2, you can add a background image and customize text colors.

Grub Customizer - settings_006

And, for Grub2 experts, you can set advanced settings much more easily than by editing the configuration files manually.

Grub Customizer - settings_007

Grub Customizer is a great addition to any Linux installation that uses Grub2!

Logical Volume Ubuntu

From HowToGeek :

In our previous article we told you what LVM is and what you may want to use it for, and today we are going to walk you through some of the key management tools of LVM so you will be confident when setting up or expanding your installation.

As stated before, LVM is a abstraction layer between your operating system and physical hard drives. What that means is your physical hard drives and partitions are no longer tied to the hard drives and partitions they reside on. Rather, the hard drives and partitions that your operating system sees can be any number of separate hard drives pooled together or in a software RAID.

To manage LVM there are GUI tools available but to really understand what is happening with your LVM configuration it is probably best to know what the command line tools are. This will be especially useful if you are managing LVM on a server or distribution that does not offer GUI tools.

Most of the commands in LVM are very similar to each other. Each valid command is preceded by one of the following:

  • Physical Volume = pv
  • Volume Group = vg
  • Logical Volume = lv

The physical volume commands are for adding or removing hard drives in volume groups. Volume group commands are for changing what abstracted set of physical partitions are presented to your operating in logical volumes. Logical volume commands will present the volume groups as partitions so that your operating system can use the designated space.

Downloadable LVM Cheat Sheet

To help you understand what commands are available for each prefix we made a LVM cheat sheet. We will cover some of the commands in this article, but there is still a lot you can do that won’t be covered here.

All commands on this list will need to be run as root because you are changing system wide settings that will affect the entire machine.

(Click on the thumbnail for a full size image)

How to View Current LVM Information

The first thing you may need to do is check how your LVM is set up. The s and displaycommands work with physical volumes (pv), volume groups (vg), and logical volumes (lv) so it is a good place to start when trying to figure out the current settings.

The display command will format the information so it’s easier to understand than the scommand. For each command you will see the name and path of the pv/vg and it should also give information about free and used space.

The most important information will be the PV name and VG name. With those two pieces of information we can continue working on the LVM setup.

Creating a Logical Volume

Logical volumes are the partitions that your operating system uses in LVM. To create a logical volume we first need to have a physical volume and volume group. Here are all of the steps necessary to create a new logical volume.

Create physical volume

We will start from scratch with a brand new hard drive with no partitions or information on it. Start by finding which disk you will be working with. (/dev/sda, sdb, etc.)

Note: Remember all of the commands will need to be run as root or by adding ’sudo’ to the beginning of the command.

fdisk -l

If your hard drive has never been formatted or partitioned before you will probably see something like this in the fdisk output. This is completely fine because we are going to create the needed partitions in the next steps.

Our new disk is located at /dev/sdb so lets use fdisk to create a new partition on the drive.

There are a plethora of tools that can create a new partition with a GUI, including Gparted, but since we have the terminal open already, we will use fdisk to create the needed partition.

From a terminal type the following commands:

fdisk /dev/sdb

This will put you in a special fdisk prompt.

Enter the commands in the order given to create a new primary partition that uses 100% of the new hard drive and is ready for LVM. If you need to change the partition size or want multiple partions I suggest using GParted or reading about fdisk on your own.

Warning: The following steps will format your hard drive. Make sure you don’t have any information on this hard drive before following these steps.

  • n = create new partition
  • p = creates primary partition
  • 1 = makes partition the first on the disk

Push enter twice to accept the default first cylinder and last cylinder.

To prepare the partition to be used by LVM use the following two commands.

  • t = change partition type
  • 8e = changes to LVM partition type

Verify and write the information to the hard drive.

  • p = view partition setup so we can review before writing changes to disk
  • w = write changes to disk

After those commands, the fdisk prompt should exit and you will be back to the bash prompt of your terminal.

Enter pvcreate /dev/sdb1 to create a LVM physical volume on the partition we just created.

You may be asking why we didn’t format the partition with a file system but don’t worry, that step comes later.


Create volume Group

Now that we have a partition designated and physical volume created we need to create the volume group. Luckily this only takes one command.

vgcreate vgpool /dev/sdb1

Vgpool is the name of the new volume group we created. You can name it whatever you’d like but it is recommended to put vg at the front of the label so if you reference it later you will know it is a volume group.

Create logical volume

To create the logical volume that LVM will use:

lvcreate -L 3G -n lvstuff vgpool

The -L command designates the size of the logical volume, in this case 3 GB, and the -n command names the volume. Vgpool is referenced so that the lvcreate command knows what volume to get the space from.

Format and Mount the Logical Volume

One final step is to format the new logical volume with a file system. If you want help choosing a Linux file system, read our how to that can help you choose the best file system for your needs.

mkfs -t ext3 /dev/vgpool/lvstuff

Create a mount point and then mount the volume somewhere you can use it.

mkdir /mnt/stuff
mount -t ext3 /dev/vgpool/lvstuff /mnt/stuff

Resizing a Logical Volume

One of the benefits of logical volumes is you can make your shares physically bigger or smaller without having to move everything to a bigger hard drive. Instead, you can add a new hard drive and extend your volume group on the fly. Or if you have a hard drive that isn’t used you can remove it from the volume group to shrink your logical volume.

There are three basic tools for making physical volumes, volume groups, and logical volumes bigger or smaller.

Note: Each of these commands will need to be preceded by pv, vg, or lv depending on what you are working with.

  • resize – can shrink or expand physical volumes and logical volumes but not volume groups
  • extend – can make volume groups and logical volumes bigger but not smaller
  • reduce – can make volume groups and logical volumes smaller but not bigger

Let’s walk through an example of how to add a new hard drive to the logical volume “lvstuff” we just created.

Install and Format new Hard Drive

To install a new hard drive follow the steps above to create a new partition and add change it’s partition type to LVM (8e). Then use pvcreate to create a physical volume that LVM can recognize.

Add New Hard Drive to Volume Group

To add the new hard drive to a volume group you just need to know what your new partition is, /dev/sdc1 in our case, and the name of the volume group you want to add it to.

This will add the new physical volume to the existing volume group.

vgextend vgpool /dev/sdc1

Extend Logical Volume

To resize the logical volume we need to say how much we want to extend by size instead of by device. In our example we just added a 8 GB hard drive to our 3 GB vgpool. To make that space usable we can use lvextend or lvresize.

lvextend -L8G /dev/vgpool/lvstuff

While this command will work you will see that it will actually resize our logical volume to 8 GB instead of adding 8 GB to the existing volume like we wanted. To add the last 3 available gigabytes you need to use the following command.

lvextend -L+3G /dev/vgpool/lvstuff

Now our logical volume is 11 GB in size.

Extend File System

The logical volume is 11 GB but the file system on that volume is still only 3 GB. To make the file system use the entire 11 GB available you have to use the command resize2fs. Just point resize2fs to the 11 GB logical volume and it will do the magic for you.

resize2fs /dev/vgpool/lvstuff

Note: If you are using a different file system besides ext3/4 please see your file systems resize tools.

Shrink Logical Volume

If you wanted to remove a hard drive from a volume group you would need to follow the above steps in reverse order and use lvreduce and vgreduce instead.

  1. resize file system (make sure to move files to a safe area of the hard drive before resizing)
  2. reduce logical volume (instead of + to extend you can also use – to reduce by size)
  3. remove hard drive from volume group with vgreduce

Backing up a Logical Volume

Snapshots is a feature that some newer advanced file systems come with but ext3/4 lacks the ability to do snapshots on the fly. One of the coolest things about LVM snapshots is your file system is never taken offline and you can have as many as you want without taking up extra hard drive space.

When LVM takes a snapshot, a picture is taken of exactly how the logical volume looks and that picture can be used to make a copy on a different hard drive. While a copy is being made, any new information that needs to be added to the logical volume is written to the disk just like normal, but changes are tracked so that the original picture never gets destroyed.

To create a snapshot we need to create a new logical volume with enough free space to hold any new information that will be written to the logical volume while we make a backup. If the drive is not actively being written to you can use a very small amount of storage. Once we are done with our backup we just remove the temporary logical volume and the original logical volume will continue on as normal.

Create New Snapshot

To create a snapshot of lvstuff use the lvcreate command like before but use the -s flag.

lvcreate -L512M -s -n lvstuffbackup /dev/vgpool/lvstuff

Here we created a logical volume with only 512 MB because the drive isn’t being actively used. The 512 MB will store any new writes while we make our backup.

Mount New Snapshot

Just like before we need to create a mount point and mount the new snapshot so we can copy files from it.

mkdir /mnt/lvstuffbackup
mount /dev/vgpool/lvstuffbackup /mnt/lvstuffbackup

Copy Snapshot and Delete Logical Volume

All you have left to do is copy all of the files from /mnt/lvstuffbackup/ to an external hard drive or tar it up so it is all in one file.

Note: tar -c will create an archive and -f will say the location and file name of the archive. For help with the tar command use man tar in the terminal.

tar -cf /home/rothgar/Backup/lvstuff-ss /mnt/lvstuffbackup/

Remember that while the backup is taking place all of the files that would be written to lvstuff are being tracked in the temporary logical volume we created earlier. Make sure you have enough free space while the backup is happening.

Once the backup finishes, unmount the volume and remove the temporary snapshot.

umount /mnt/lvstuffbackup
lvremove /dev/vgpool/lvstuffbackup/

Deleting a Logical Volume

To delete a logical volume you need to first make sure the volume is unmounted, and then you can use lvremove to delete it. You can also remove a volume group once the logical volumes have been deleted and a physical volume after the volume group is deleted.

Here are all the commands using the volumes and groups we’ve created.

umount /mnt/lvstuff
lvremove /dev/vgpool/lvstuff
vgremove vgpool
pvremove /dev/sdb1 /dev/sdc1

That should cover most of what you need to know to use LVM. If you’ve got some experience on the topic, be sure to share your wisdom in the comments

Marionnet

Marionnet : un laboratoire virtuel de réseau. Dommage qu’il ne soit pas fourni de tutoriel et de cas d’école.

« Page précédentePage suivante »