Восстановление пароля MySQL

Останавливаем сервис:

# /etc/init.d/mysql stop

и перезапускаем его вручную с опцией игнорирования привелегий:

# mysqld_safe –skip-grant-tables &

Теперь мы можем задать новый пароль:

# mysql -u root

mysql> use mysql;
mysql> update user set password=PASSWORD(”НОВЫЙ ПАРОЛЬ”) where User=’root’;
mysql> flush privileges;
mysql> quit

И перезапускаем MySQL в штатном режиме:

# /etc/init.d/mysql restart

 

Debian sources.list

# cat /etc/apt/sources.list

# Main Debian mirror
deb http://mirror.yandex.ru/debian/ squeeze main contrib non-free
#deb-src http://mirror.yandex.ru/debian/ squeeze main contrib non-free

# Security fixes
deb http://mirror.yandex.ru/debian-security/ squeeze/updates main contrib non-free
#deb-src http://mirror.yandex.ru/debian-security/ squeeze/updates main contrib non-free
# Debian Backports.org repo
deb http://mirror.yandex.ru/backports.org/ squeeze-backports main contrib non-free

# Debian multimedia archive
deb http://mirror.yandex.ru/debian-multimedia/ squeeze main

# Opera
deb http://mirror.yandex.ru/debian-opera/ squeeze non-free

# Opera Beta
#deb http://mirror.yandex.ru/debian-opera-beta/ squeeze non-free

# VirtualBox
#deb http://mirror.yandex.ru/debian-virtualbox/ squeeze non-free

# Google progs repo
#deb http://dl.google.com/linux/deb/ squeeze non-free

# I-rs openoffice repo
deb http://download.i-rs.ru/pub/openoffice/debian/ ./

# Local repository
# deb file:/var/localrepository/ squeeze main
# For nvidia drivers
#deb http://ftp.ru.debian.org/debian/ sid non-free

В Debian 5 используется имя дистрибутива lenny, в Debian 6 используется squeeze.

GRUB2

 

The Grub 2 Guide
(formerly Grub 2 Basics)

GRUB Customizer — Finally a comprehensive GUI Configuration Tool !
Daniel Richter has developed a graphical Grub2 configuration application. It’s an excellent step in making Grub2 menu changes simpler for the average user. It provides users with a method of altering their Grub2 menus without using the command line and obscure commands. The application is available from this Launchpad page. How it works is detailed in this FAQ. Here is the Ubuntu Forum HOWTO on Grub Customizer:
Grub Customizer
Thank you Daniel!

GRUB Changes to /etc/default/grub Options
Grub 1.98 has made some changes, and Grub 1.99 is making more to the options available in /etc/default/grub. To see the current options available to /etc/default/grub for your version:

Code:
strings /usr/sbin/grub-mkconfig | grep "export GRUB" -A 30

For instance, in Grub 1.98 and earlier, the /etc/default/grub entry to hide «Recovery» menu entries was «GRUB_DISABLE_LINUX_RECOVERY=true». In G2 1.99 it is currently «GRUB_DISABLE_RECOVERY=true».

New Wubi Megathread Guide
Forum member Rubi1200 has written an excellent comprehensive guide on resolving Wubi-related problems. View the «Wubi Megathread» at http://ubuntuforums.org/showthread.php?t=1639198

Grub Submenu
Test versions of Ubuntu 11.04 (Natty Narwhale) are being released with Grub 1.99. One of the new features is the use of the Submenu. The submenu is still being tweaked, but should hide older kernels in the main OS. Clicking on the Submenu entry will reveal the underlying older kernels. Using a Submenu kernel as the default initially was not possible, but a patch has been submitted by Colin Watson. The user will be able to use either the exact menuentry title or the «saved» function in /etc/default/grub’s GRUB_DEFAULT= setting to set a submenu default. The use of a number in GRUB_DEFAULT is currently not possible. More details as they become available.

 

  1. Introduction
  2. First Look Differences
  3. Improvements
  4. Booting Grub
  5. Grub 2 Files & Options
  6. Adding Entries to Grub 2
  7. Removing Entries from Grub 2
  8. Grub 2 Splash Images & Theming
  9. Changing Menu Resolution
  10. Password Protection
  11. Booting to Recovery Mode w/o Menu Option
  12. Uninstalling GRUB 2 > GRUB
  13. Reinstalling GRUB 2 from the LiveCD
  14. Booting to LiveCD ISO
  15. Booting from the Rescue Mode
  16. Restoring GRUB2 / XP / Vista / Win 7 Bootloaders
  17. Grub Rescue Image
  18. Grub 2 Fallback Option
  19. Selected Problems & Bugs
  20. Links

 

  1. Introduction
    I’ve written this guide to present some basic information about Grub 2. It is meant for users who may be familiar with basic editing of the original Grub (Grub Legacy) menu.lst and wonder how it carries over to Grub 2. The current version of Grub 2 is 1.98; Ubuntu 9.10, Karmic Koala was the first Ubuntu release to use Grub 2 on new installations by default (1.97~beta4). In keeping with Ubuntu’s «stable release» philosophy, 1.97~beta4 will probably remain the official version in 9.10/Karmic and will not be updated to 1.98. In this guide, any reference to Grub 2 will refer to 1.98 unless otherwise noted. The user can check their current version with the «grub-install -v» command.StartUp-Manager supports Grub 2, but not all options are available. The two most-used items, however, are: setting the default kernel/OS and setting the menu timeout delay. There are plans for a StartUp-Manager 2 that works only for Grub 2 but it is still under development according to its creator. To view a guide on installing and running StartUpManager, view the StartUpManager community doc or the forum post on which it was based: http://ubuntuforums.org/showthread.php?t=818177

    Official documentation at this point is still being created, which is partly the reason for this post. More comprehensive and complete documentation will hopefully be forthcoming from the developers and volunteers. Of the existing documentation, I have have provided several links to the better sources at the end of this post.

    For troubleshooting and modifying the Grub menu, it is important to know which version you are using (Grub legacy, 0.97; Grub 2 in Karmic 1.97~beta4; Grub 2 in Lucid 1.9. To confirm the version of Grub used in your system, run this command:

    Code:
    grub-install -v

    Which should produce something like this:

    Quote:
    drs305@mycomputer:~$ grub-install -v
    grub-install (GRUB) 1.98+20100804-5ubuntu3
  2. First Look Differences: GRUB vs GRUB 2
    At first boot, there will not be much difference in what the user sees on the boot menu. The one exception is a clean install of Ubuntu with no other installed operating system(s). In this case, GRUB 2 will boot directly to the login prompt or Desktop without displaying a menu. Other major differences:

    • No »/boot/grub/menu.lst». It has been replaced by »/boot/grub/grub.cfg».
    • Hold down SHIFT to display the hidden menu during boot (formerly ESC is GRUB legacy).
    • There is no «find /boot/grub/stage1» at the grub prompt. Stage 1.5 has also been eliminated.
    • The main menu file, »/boot/grub/grub.cfg» is not meant to be edited, even by ‘root’.
    • »grub.cfg» is overwritten anytime there is a update, a kernel is added/removed or the user runs `update-grub` *
    • A pre-made custom file, »/etc/grub.d/40_custom», is available in which users can place their own entries. This file will not be overwritten by Grub updates.
    • The primary configuration file for changing menu display settings is »/etc/default/grub».
    • There are multiple files for configuring the the menu — »/etc/default/grub» mentioned above, and all the scripts in /etc/grub.d/ folder.
    • Other operating systems, such as Windows, should automatically be recognized and added to the menu.
    • No changes made in the configuration files will take effect until the `update-grub` command is also run.

    * To update the GRUB 2 menu, the command sudo update-grub will be used throughout this guide. update-grub actually runs the command «grub-mkconfig -o /boot/grub/grub.cfg» This runs several scripts and incorporates the results into/boot/grub/grub.cfg which detemines what is seen on the screen during boot. Since the GRUB 2 developers do not intend to remove the update-grub ‘stub’, it will be used for simplicity and ease of use.

  3. Improvements
    GRUB 2’s major improvements over the original GRUB include:

    • New configuration file structure
    • Scripting support including conditional statements and functions
    • Dynamic module loading
    • Rescue mode
    • Themes — under (very slow development). Users wishing to use theming should search the Internet for «burg».
    • Graphical boot menu support and improved splash capability
    • Boot Ubuntu LiveCD and some other ISO images directly from hard drive
    • Non-X86 platform support (such as PowerPC)
    • Universal support for UUIDs (not just Ubuntu)
    • Improved internationalization, including support for non-ASCII characters
  4. Booting Grub
    Grub 2 loads before the operating system. It’s modular components are loaded on an as-needed basis. Menu display behavior is generally determined by settings in /etc/default/grub. Review the «Grub 2 Files & Options» section for specific entry and formatting guidance.The main options for displaying the menu are:

    • Initial Default
      • Grub 2 will boot straight into the default operating system if no other operating system is detected. No menu will be displayed. If another operating system is detected, the Grub 2 menu will display.
    • Timed display.
      • The default delay is 10 seconds. If no user input is made Grub 2 boots to the default entry.
      • The countdown can be stopped by pressing any key. The user must then make a selection manually.
      • The booted entry is determined by the DEFAULT= setting in /etc/default/grub, The first «menuentry» is 0.
    • Hidden
      • The user can interrupt the boot process and display the menu by holding down the SHIFT key until the menu displays. Grub 2 searches for a depressed SHIFT key signal during boot. If the key is pressed or Grub 2 cannot determine the status of the key, the menu is displayed. Note: The «SHIFT» keystatus check is currently nested within in a conditional statement within /etc/grub.d/30_os-prober and may not work under certain circumstances.
      • The time the screen remains blank but available for display is determined by a setting in /etc/default/grub.
      • To provide visual feedback during while the countdown continues, a countdown display can be shown on the screen.
      • At the end of the timeout, the default entry determined in /etc/default/grub will be selected.
    • Saved
      • If the default option is set to «saved», the last kernel/system successfully booted will be selected and run if no input is made.
      • Unlike GRUB, GRUB 2 stores the «saved» entry as a string, not as a menu position number. In GRUB 2, the result is applied more consistently. Example: If the first entry (kernel -15) becomes the second entry due to a kernel update, it will still be the «saved» entry even though it’s position on the menu has changed.
  5. Grub 2 Files & Options
    Many of the files in /boot/grub will not be recognizable by users of Grub Legacy. Especially noticeable are the multitude of *.mod files. Grub 2 is modular and these files are loaded as necessary by the grub bootloader.The Grub 2 user-configurable settings are contained mainly in /etc/default/grub and the files in /etc/grub.d. When update-grub is executed the results are input into the /boot/grub/grub.cfg file.

    • /boot/grub/grub.cfg
      • This is the main Grub 2 file. It «replaces» Grub Legacy’s /boot/grub/menu.lst This file contains the Grub menu information but unlike Grub Legacy’s menu.lst file, grub.cfg is not meant to be edited.
        • grub.cfg is automatcially generated when «update-grub» is executed:
        • Each section (### BEGIN) is clearly delineated and references the file in the /etc/grub.d folder from which the information was generated.
        • grub.cfg is updated by running the «update-grub» or «update-grub2» command as root.
        • By default, and whenever the «update-grub» command is executed, this file is made «read-only». This is in keeping with the intent that the file should not be edited manually. If you must edit this file, instructions are provided in Section 2.
      • Sample grub.cfg including Windows and one manual entry (40_custom):
        Code:
        #
        # DO NOT EDIT THIS FILE
        #
        # It is automatically generated by grub-mkconfig using templates
        # from /etc/grub.d and settings from /etc/default/grub
        #
        
        ### BEGIN /etc/grub.d/00_header ###
        if [ -s $prefix/grubenv ]; then
          set have_grubenv=true
          load_env
        fi
        set default="${saved_entry}"
        if [ "${prev_saved_entry}" ]; then
          set saved_entry="${prev_saved_entry}"
          save_env saved_entry
          set prev_saved_entry=
          save_env prev_saved_entry
          set boot_once=true
        fi
        
        function savedefault {
          if [ -z "${boot_once}" ]; then
            saved_entry="${chosen}"
            save_env saved_entry
          fi
        }
        
        function recordfail {
          set recordfail=1
          if [ -n "${have_grubenv}" ]; then if [ -z "${boot_once}" ]; then save_env recordfail; fi; fi
        }
        
        function load_video {
          insmod vbe
          insmod vga
        }
        
        insmod part_msdos
        insmod ext2
        set root='(hd0,msdos9)'
        search --no-floppy --fs-uuid --set 1c4adc10-a208-4373-b842-9851a8421da7
        if loadfont /usr/share/grub/unicode.pf2 ; then
        set gfxmode=800x600
          load_video
          insmod gfxterm
        fi
        terminal_output gfxterm
        insmod part_msdos
        insmod ext2
        set root='(hd0,msdos9)'
        search --no-floppy --fs-uuid --set 1c4adc10-a208-4373-b842-9851a8421da7
        set locale_dir=($root)/boot/grub/locale
        set lang=en
        insmod gettext
        if [ "${recordfail}" = 1 ]; then
          set timeout=-1
        else
          set timeout=3
        fi
        play 480 440 1
        ### END /etc/grub.d/00_header ###
        
        ### BEGIN /etc/grub.d/05_debian_theme ###
        insmod part_msdos
        insmod ext2
        set root='(hd0,msdos7)'
        search --no-floppy --fs-uuid --set 8144779b-ad38-4c1c-aa45-35065ad289e5
        insmod png9851a8421da9
        if background_image /docs2/computer/backgrounds/grub.backgrounds/bg_earth.800x600.png ; then
          set color_normal=light-gray/black
          set color_highlight=green/black
        else
          set menu_color_normal=white/black
          set menu_color_highlight=black/light-gray
        fi
        ### END /etc/grub.d/05_debian_theme ###
        
        ### BEGIN /etc/grub.d/10_linux ###
        menuentry 'Ubuntu, with Linux 2.6.35-22-generic' --class ubuntu --class gnu-linux --class gnu --class os {
        	recordfail
        	insmod part_msdos
        	insmod ext2
        	set root='(hd0,msdos9)'
        	search --no-floppy --fs-uuid --set 1c4adc10-a208-4373-b842-9851a8421da7
        	linux	/boot/vmlinuz-2.6.35-22-generic root=UUID=1c4adc10-a208-4373-b842-9851a8421da7 ro   quiet splash
        	initrd	/boot/initrd.img-2.6.35-22-generic
        }
        menuentry 'Ubuntu, with Linux 2.6.35-22-generic (recovery mode)' --class ubuntu --class gnu-linux --class gnu --class os {
        	recordfail
        	insmod part_msdos
        	insmod ext2
        	set root='(hd0,msdos9)'
        	search --no-floppy --fs-uuid --set 1c4adc10-a208-4373-b842-9851a8421da7
        	echo	'Loading Linux 2.6.35-22-generic ...'
        	linux	/boot/vmlinuz-2.6.35-22-generic root=UUID=1c4adc10-a208-4373-b842-9851a8421da7 ro single 
        	echo	'Loading initial ramdisk ...'
        	initrd	/boot/initrd.img-2.6.35-22-generic
        }
        ### END /etc/grub.d/10_linux ###
        
        ### BEGIN /etc/grub.d/20_linux_xen ###
        ### END /etc/grub.d/20_linux_xen ###
        
        ### BEGIN /etc/grub.d/20_memtest86+ ###
        menuentry "Memory test (memtest86+)" {
            insmod ext2
            set root='(hd0,1)'
            search --no-floppy --fs-uuid --set 444539ba-ab9e-4028-94f5-c1a86b5ec7c1
            linux16    /boot/memtest86+.bin
        }
        ### END /etc/grub.d/20_memtest86+ ###
        
        ### BEGIN /etc/grub.d/30_os-prober ###
        menuentry "Microsoft Windows XP Home Edition (on /dev/sda1)" {
            set root=(hd0,1)
            chainloader +1
        }
        ### END /etc/grub.d/30_os-prober ###
        
        ### BEGIN /etc/grub.d/40_custom ###
        exec tail -n +3 $0
        # This file provides an easy way to add custom menu entries.  Simply type the
        # menu entries you want to add after this comment.  Be careful not to change
        # the 'exec tail' line above.
        
        menuentry 'Maverick' {
        	insmod ext2
        	set root='(hd0,9)'
        	search --no-floppy --fs-uuid --set 1c4adc10-a208-4373-b842-9851a8421da7
        	linux /vmlinuz root=UUID=1c4adc10-a208-4373-b842-9851a8421da7 ro quiet splash acpi_enforce_resources=lax
        	initrd /initrd.img
        }
        
        ### END /etc/grub.d/40_custom ###
    • /etc/default/grub
      • This file contains information formerly contained in the upper section of Grub Legacy’s menu.lst and items contained on the end of the kernel line. The items in this file can be edited by a user with administrator (root) privileges.
        Quote:
        # If you change this file, run ‘update-grub’ afterwards to update
        # /boot/grub/grub.cfg.GRUB_DEFAULT=0
        #GRUB_HIDDEN_TIMEOUT=0
        GRUB_HIDDEN_TIMEOUT_QUIET=true
        GRUB_TIMEOUT=10
        GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
        GRUB_CMDLINE_LINUX_DEFAULT=»quiet splash»
        GRUB_CMDLINE_LINUX=»»

        # Uncomment to disable graphical terminal (grub-pc only)
        #GRUB_TERMINAL=console

        # The resolution used on graphical terminal
        # note that you can use only modes which your graphic card supports via VBE
        # you can see them in real GRUB with the command `vbeinfo’
        #GRUB_GFXMODE=640×480

        # Uncomment if you don’t want GRUB to pass «root=UUID=xxx» parameter to Linux
        #GRUB_DISABLE_LINUX_UUID=true

        # Uncomment to disable generation of recovery mode menu entries
        #GRUB_DISABLE_LINUX_RECOVERY=»true»

        # Uncomment to get a beep at grub start
        #GRUB_INIT_TUNE=»480 440 1″

    • GRUB_DEFAULT — Sets the default menu entry. Entries may be numeric or «saved»
      • GRUB_DEFAULT=0 — Sets the default menu entry by menu position. As Grub Legacy, the first «menuentry» in grub.cfg is 0, the second is 1, etc.
      • GRUB_DEFAULT=saved — (Grub 1.98) Enables the «grub-reboot» and «grub-set-default» commands.
        • This setting allows the use of the following commands to set a default OS. The default OS will not be set merely by an interactive selection of an OS from the menu.
        • grub-set-default. Sets the default boot entry until changed.
          • The format is «sudo grub-set-default X, with X being the menuentry position (starting with 0 as the first entry) or the exact menu string. Examples: sudo grub-set-default 3 or sudo grub-set-default «Ubuntu, Linux 2.6.32-15-generic»
          • To obtain the existing menuentry choice number (starting from 0) or the menuentry «string», run «grep menuentry /boot/grub/grub.cfg»
        • grub-reboot. This command sets the default boot entry for the next boot only. The format of the command is the same as for «grub-set-default» (see above).
        • For an example of how to enable the «saved» option with a custom menu, see the «Custom User Entries» section.
      • GRUB_DEFAULT=»xxxx» — An exact menu entry, including the quotation symbols, may also be used. In this case, location in the menu will not matter. Example: GRUB_DEFAULT=»Ubuntu, Linux 2.6.31-9-generic»
    • GRUB_SAVEDEFAULT=true* If set to true this setting will automatically set the last selected OS from the menu as the default OS on the next boot. No commands need be run to set the default OS. For this entry to work, theGRUB_DEFAULT entry should be set to saved.
    • GRUB_TIMEOUT=10 — No change from Grub Legacy. This is the number of seconds before the default entry is automatically booted.
      • Setting this value to -1 will cause the menu to display until the user makes a selection.
      • To display the menu on each boot use a value of 1 or higher.
      • This command defers to the GRUB_HIDDEN_TIMEOUT command. If the GRUB_HIDDEN_TIMEOUT option is interrupted by pressing the SHIFT key, the GRUB_TIMEOUT counter begins its countdown.
      • Caution: Holding down the «SHIFT» key will not display the menu if «GRUB_TIMEOUT=» is set to «0» .
      • In addition to editing the file as root, you can also run the following commands the check and change the default timeout value. The first checks the existing timeout, the second replaces the value. Replace T with the new value.
        Code:
        cat /etc/default/grub | grep 'GRUB_TIMEOUT='   # Checks current TIMEOUT value.
        sudo sed 's/GRUB_TIMEOUT=10/GRUB_TIMEOUT=T/g' -i /etc/default/grub  # Change TIMEOUT value. Replace T with new value.
    • GRUB_HIDDEN_TIMEOUT=0
      • Wait X seconds for a key to be pressed before displaying the menu. If no key is pressed during that time, boot immediately.
    • GRUB_HIDDEN_TIMEOUT_QUIET=true
      • Used with the GRUB_HIDDEN_TIMEOUT setting.
      • true — No countdown is displayed. The screen will be blank.
      • false — A counter will display on a blank screen for the duration of the GRUB_HIDDEN_TIMEOUT value.
      • This feature currently appears to be broken; the timeout counter isn’t appearing when set to ‘false’ or not set.
    • GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
      • Determines the descriptive name in the menu entry. (Ubuntu, Xubuntu, Debian, etc.)
    • GRUB_CMDLINE_LINUX
      If it exists, this line imports any entries to the end of the ‘linux’ command line (Grub Legacy’s «kernel» line) for both normal and recovery modes. This is similar to the «altoptions» line in menu.lst
    • GRUB_CMDLINE_LINUX_DEFAULT=»quiet splash»
      This line imports any entries to the end of the ‘linux’ line (Grub Legacy’s «kernel» line). The entries are appended to the end of the normal mode only. This is similar to the «defoptions» line in menu.lst. For a black screen with boot processes displayed in text, remove «quiet splash». To see the grub splash image plus a condensed text output, use «splash». This line is where other instructions, such as «acpi=off» are placed.For the GRUB_CMDLINE_LINUX_DEFAULT and GRUB_CMDLINE, quotation marks are required (single or double) if the entry is more than one alphanumeric entry. For example, quiet splash requires single or double quotes, while an entry such as quiet would not.
    • #GRUB_TERMINAL=console
      Uncomment to disable graphical terminal (grub-pc only). This can be useful if the user plans on spending a lot of time in the GRUB 2 command line mode. Scrolling and screen responsiveness will be greatly speeded up. If enabled, Grub background splash images will not be displayed.
    • #GRUB_DISABLE_LINUX_UUID=true
      Uncomment if you don’t want GRUB to pass «root=UUID=xxx» parameter to Linux
      Update: A bug requires quotation symbols be added for this option to be enabled. Change true to «true» and uncomment the line to eliminate UUIDs for linux entries.
    • #GRUB_GFXMODE=640×480
      You can add this line and remove the # symbol to make it active. This entry sets the resolution of the graphical menu (the menu text size). It provides resolutions supported by the user’s graphics card (e.g. 640×480, 800×600, 1280×1024, etc). The setting applies only to the boot menu text.
    • From the GRUB 2 menu you can display available resolutions by typing «c» and then at the «grub>» prompt type «vbeinfo»
    • GRUB_DISABLE_LINUX_RECOVERY=true (GRUB 1.98 & earlier) or GRUB_DISABLE_RECOVERY=true (GRUB 1.99 & later)Add or uncomment this line to prevent «Recovery» mode kernel options from appearing in the menu. If you want a «Recovery» option for only one kernel, make a special entry in /etc/grub/40_custom.
    • GRUB_DISABLE_OS_PROBER=»true»* Enables/disables the os-prober check of other partitions for operating systems, including Windows, Linux, OSX and Hurd.
    • GRUB_INIT_TUNE=»480 440 1″
      • Introduced in Grub 1.98 (Lucid)
      • When uncommented, plays a single beep just prior to the Grub 2 menu display.
      • The format unless a file is named is: «tempo [pitch1 duration1] [pitch2 duration2] …»
      • The duration is based on the tempo. A tempo of 60 gives the duration a value of 1 second, 120 is .5, 240 is .25, 480 is .125, etc. The length of the tone can be changed by modifying either the tempo (all tones) or duration (individual tone).
        • Just a bit of fun:
          • Warning: The menu will not be displayed until the tone is finished
          • Close Encounters/5 Tone:GRUB_INIT_TUNE=»480 900 2 1000 2 800 2 400 2 600 3″
          • Fur Elise (note long):GRUB_INIT_TUNE=»480 420 1 400 1 420 1 400 1 420 1 315 1 370 1 335 1 282 3 180 1 215 1 282 1 315 3 213 1 262 1 315 1 335 3 213 1 420 1 400 1 420 1 400 1 420 1 315 1 370 1 335 1 282 3 180 1 215 1 282 1 315 3 213 1 330 1 315 1 282 3″
      • Online documentation is available by typing «info grub —index-search play» in a terminal.

      * Entries which are not found in the default file and must be added by the user.

    • /etc/grub.d/
      • The files in this folder are read during execution of «update-grub» or «update-grub» commands. The contents are imported into /boot/grub/grub.cfgThe order of the entries in the grub menu is based on the order of the file names. File named with a starting numeral are run before those beginning with a letter. The order the files are run determines the menu order in grub.cfg.
        Custom entries can be added to the «40_custom» file or in a newly created file.

        Any file created must be executable in order to be included in the grub.cfg file during the «update-grub» command.

        • 00_header
        • 05_debian_theme: Set background and text colors, themes
        • 10_hurd Locates Hurd kernels
        • 10_linux Locates Linux kernels based on results of the «lsb_release» command.
        • 10_lupin Locates Linux kernels in Wubi installs within Windows, among other things.
        • 20_memtest86+: If the file /boot/memtest86+.bin exists, it is included as a menu item.
        • 30_os-prober: Searches for Linux and OS’s on other partitions and includes them in the menu.
        • 40_custom: A template for adding custom menu entries which will be inserted into grub.cfg upon execution of the «update-grub» command. This and any other custom file must be made executable to allow importation intogrub.cfg.
  6. Adding Entries to Grub 2
    Menu entries can be added to grub.cfg automatically or manually.

    • Automatically.
      • When «update-grub» or «update-grub» is executed, Grub 2 will search for linux kernels and other Operating Systems. What and where is looks is based on the files contained in /etc/grub.d folder.
        • 10_linux searches for installed linux kernels on the same partition.
        • 30_os-prober searches for other operating systems.
    • Custom User Entries (/etc/grub.d/40_custom).
      • Entries to grub.cfg can be manually inserted by creating a file in the /etc/grub.d folder.
        • The name of the file determines the order in the menu. 30_os-prober entries will be placed before 40_custom entries, which will be placed before 50_my-sample entries.
        • Any created file must be made executable. This can be done as root by running «sudo chmod +x /etc/grub.d/filename«.
        • The files in the /etc/grub.d folder will be read and the contents included in grub.cfg when the «update-grub» command is executed as root.
      • A sample entry. This file creates a menu item for running the SystemRescueCD (previously installed) from a partition created on sda10. Folders and files must have been copied to the correct location in accordance with the SystemRescueCD if you wish to actually use this entry. Note this entry will not work for a SystemRescue ISO. See Section 14 for instructions on how to add an entry to boot ISO images.
        • Quote:
          #!/bin/sh
          exec tail -n +3 $0
          # This file provides an easy way to add custom menu entries. Simply type the
          # menu entries you want to add after this comment. Be careful not to change
          # the ‘exec tail’ line above.menuentry «System Rescue CD» {
          set root=(hd0,10)
          linux /sysrcd/rescuecd subdir=sysrcd setkmap=us
          initrd /sysrcd/initram.igz
          }
        • Note the new partition naming convention. Devices start counting from «0» as done previously. sda is designated as «hd0», sdb is «hd1», etc. However the first partition is now designated as sda1. Counting partitions does notstart with «0». sda5 is «5».
        • If the user wishes to get visual confirmation in the terminal that the 40_custom file contents are being added when «update-grub» is executed, the following line can be added to the /etc/grub.d/40_custom file:
          • Quote:
            echo «Adding 40_custom menu entries.» >&2
          • Place this line immediately after the first line — «#!/bin/bash» — and before the «exec tail -n +3 $0» line.
      • Tip: If you want to have your custom entries at the top of the menu (say you want custom titles), create a new file and name it «07_xxxx». Since the files in /etc/grub.d/ are read sequentially, those in «07_custom» will be placed before those of «10_linux». I recommend not naming a custom menu file lower than 06 so that any theme run from 05_debian_theme is allowed to run before any custom menu is created. After creating the file, run sudo update-gruband then check the value of «DEFAULT» in /etc/default/grub. If it doesn’t point to the correct menuentry, change the value of DEFAULT to the correct menuentry value.
      • Omitting memtest86+: To prevent «memtest86+» entries in your Grub 2 menu, remove the «executable» bit from /etc/grub.d/20_memtest86+. You can do this via a file browser by selecting «Properties (right click), Permissions», or via the command line:
        Code:
        sudo chmod -x /etc/grub.d/20_memtest86+
      • Omitting Recovery Mode entries:The file /etc/grub.d/10_linux was recently updated to include a check for recovery mode options. Edit /etc/default/grub and add or change this line:
        Quote:
        GRUB_DISABLE_LINUX_RECOVERY=true # GRUB 1.98 & earlier
        GRUB_DISABLE_RECOVERY=true # GRUB 1.99 & later

        If you have an older version of /etc/grub.d/10_linux and the above does not work after updating grub, you can prevent «Recovery mode» entries in your Grub 2 menu, by editing /etc/grub.d/10_linux. If there are no conditional «if» statements concerning the recovery mode, place a comment symbol (#) in front of the following lines (at approximately line 146) of the old file:

        Quote:
        # linux_entry «${OS}, Linux ${version} (recovery mode)» \
        # «single ${GRUB_CMDLINE_LINUX}»

        If you wish to retain one «Recovery mode» entry for insurance, you can add an entry to /etc/grub.d/40_custom which will appear at the bottom of your grub menu.

      • Building a Totally Customized Menu: Ok, admit you are a control freak and you want to see only what you build yourself — customized titles, no «memtest86+» and no extra kernels. Here is how you do it:
        • Run sudo update-grub to get the current available kernels.
        • Copy the desired «menuentry» listings from /boot/grub/grub.cfg to /etc/grub.d/40_custom The entry begins with the line starting with «menuentry» and ends with a line containing «}».
        • Add any other «menuentry» items you wish to see on the boot menu.
        • Edit the titles of the «menuentry» line if desired (between the quotation symbols). Do not change the lines following the «menuentry» line. Each entry should start with a «menuentry» line and end with a «}» on the last line.
        • Remove the executable bit from /etc/grub.d/10_linux, /etc/grub.d/20_memtest86+ and /etc/grub.d/30_os-prober
          Removing the executable bit from any file in /etc/grub.d will exclude the file from being included in grub updates.

          Code:
          sudo chmod -x /etc/grub.d/10_linux /etc/grub.d/20_memtest86+ /etc/grub.d/30_os-prober
        • Run «sudo update-grub»
        • The updated /boot/grub/grub.cfg file should now contain only sections for «00_header», «05_debian_theme» and «40_custom».
        • The grub.cfg file will not be updated with the addition of a new kernel. To add a new kernel, make «10_linux» executable, run «sudo update-grub» to refresh the available kernels, and repeat these instructions.
      • Don’t forget to run «sudo update-grub» after making any changes to your /etc/grub.d files.
    • Manual Editing of grub.cfg (Not encouraged)
      Manual editing of /boot/grub/grub.cfg is not encouraged. Think of grub.cfg as a result, not as an initiator. The files that should be edited are contained in the /etc/grub.d folders and the /etc/default/grub file.In order to discourage its editing, grub.cfg is read-only. If you must edit this file:

      Code:
      gksudo gedit /boot/grub/grub.cfg

      Note: This file is returned to ‘read-only’ status anytime the update-grub command is run.

  7. Removing Entries from Grub 2
    Entries should be removed by editing or removing files in the /etc/grub.d folder. The /boot/grub/grub.cfg file is read-only and should not normally require editing.

    • Automatically.
      • Too Many Kernels?
        • If you are not sure of the kernel you are currently using, in a terminal type «uname -r».
        • Kernels removed via APT (Synaptic, «apt-get remove», etc.) will automatically update grub.cfg and no user action is required. A great tool for removing kernels (and menu entries) is Ubuntu-Tweak, a safe and easy-to-use GUI app.
        • Many users keep one previous kernel known to work on the machine as a backup.
          • Synaptic
            • Type the kernel number in the search window at the upper right (for example — 2.6.28-11).
            • Find the «linux-image» and «linux-headers» files for the applicable kernel (example — linux-image-2.6.26-11 or «linux-image-2.6.26-11-generic).
            • Right click and select «Mark for Complete Removal» and then press the Apply main menu button.
            • The kernels will be removed from your system and from the Grub menu.
          • Ubuntu-Tweak
            • Go to the Ubuntu-Tweak download page.
            • Add the repository as per the instructions, or download the file manually and double-click the .deb file to install.
            • Ubuntu-Tweak will be available under Applications > System Tools.
            • To clean the kernels:
              • Select «Package Cleaner» on the left and «»Clean Kernel» from the right panel.
              • Press the «Unlock» button at the lower right, enter your password.
              • Select from the displayed list the kernel images and headers you wish to remove. The kernel in use is not listed.
              • Press the «Cleanup» button at the lower right to remove the selected kernel images and headers.
          • Too Many Operating Systems?
            • Other Operating Systems which have been removed from the computer will also be removed from the menu once «update-grub» is run as root.
            • Menu items are placed on the Grub2 menu by scripts. If you don’t want other Operating Systems to be entered in the menu, disable /etc/grub.d/30_osprober
              • Run this command to stop the script from running: sudo chmod -x /etc/grub.d/30_os-prober
              • DISABLE_30_OS_PROBER=’true’ in /etc/default/grub
          • Memtest86+
            • Code:
              sudo chmod -x /etc/grub.d/20_memtest86+
        • Run the update-grub command to allow the changes to be incorporated in grub.cfg
    • User-Created Entries.
      • To remove a user-created menu entry, remove the applicable file from the /etc/grub.d folder.
      • If a custom file contains multiple entries, individual items may be removed and others retained.
      • Once the file has been removed or edited, run «update-grub» to update grub.cfg.
  8. Grub 2 Splash Images & Theming
    Why reinvent the wheel? Visit this site for an excellent presentation on creating Grub 2 images:
    http://members.iinet.net/~herman546/p20/GRUB2%20Splashimages.htmlHowever, if encrypted disks are not an issue, here are the basics:

    • Manually copy grub splash images into the /usr/share/images/grub folder or install the default grub2 splash images via Synaptic or:
      Code:
      sudo apt-get install grub2-splashimages
    • The grub2’s splash images are normally, but not always, controlled by /etc/grub.d/05_debian_theme. There are additional options in Grub 1.99 & later, and 2 variants in Grub 1.98 (see below).
      • Grub 1.98 late + Grub 1.99 (Maverick / Natty )
        Rather than edit the /etc/grub.d/05_header or /usr/share/desktop-base/grub_background.sh file, the user can now include the background image designation directly into /etc/default/grub. The path assumes the folder is located in the default system partition.

        Quote:
        GRUB_BACKGROUND=/path/filename

        Example: GRUB_BACKGROUND=»/home/my_username/grub_images/my_grubimage.png»

      • Grub 1.98 (Lucid)
        For Grub 1.98, attempt to open the following two files for editing:

        Code:
        gksudo gedit /usr/share/desktop-base/grub_background.sh /etc/grub.d/05_debian_theme
        • If the file /usr/share/desktop-base/grub_background.sh is empty/blank, edit /etc/grub.d/05_debian_theme
        • If the file /usr/share/desktop-base/grub_background.sh exists, edit this file and not /etc/grub.d/05_debian_theme.

        Find the following line and edit the highlighted area, replacing it with the path and grub splash image you wish to use:

        Quote:
        WALLPAPER=»/<path-to-image>/<your-image-name-here-including-extension>»

        Example: WALLPAPER=»/home/my_username/grub_images/my_grubimage.png»

      • Grub 1.97~beta4
        Find the following line and edit the highlighted area, replacing it with the grub splash image you wish to use (and located in /usr/share/images/grub):

        Quote:
        for i in {/boot/grub,/usr/share/images/grub}/moreblue-orbit-grub.{png,tga} ; do

        Note: There is a period ( . ) following the filename.

        • At one point Grub 2 splash images were downloaded and stored in /usr/share/images/desktop.base If this is where your grub images are stored, change the address in the previous command accordingly ( … /usr/share/images/desktop-base} … ).
    • Save the file, then update grub2:
      Code:
      sudo update-grub

    A Note About Grub 2 Theming

  9. Changing Menu Resolutions
    If the user wishes to change the resolution of the GRUB 2 screen while using a splash image follow these steps:

    1. Set the desired resolution in /etc/default/grub
      • Change the value of GRUB_GFXMODE= (Example: GRUB_GFXMODE=800×600)
        • If unsure of what resolutions are available to GRUB 2 they can be displayed by typing vbeinfo in the GRUB 2 command line. The command line is accessed by typing «c» when the main GRUB 2 menu screen is displayed.
    2. Select an image of the same size and make the change in /etc/grub.d/05_debian_theme
      • The image name is located in the line beginning with «WALLPAPER=» (Grub 1.9 or » for i in {/boot» in Grub 1.97-beta.
      • If an image of the correct size is not used, the menu may not be positioned correctly.
      • Use the image editor of your choice to create/resize an image to the correct size.
      • The user may be able to view the image size via Properties in a file browser (check the Properties Image tab in Nautilus).
      • Images must be .tga, .png, or .jpg (8-bit) images, saved in RGB format (non-indexed).
    3. Run update-grub as root to add the new settings to /boot/grub/grub.cfg
  10. Basic Password Protection Note: To reduce the size of this entry, a separate post with information on establishing Grub 2 password protection is located on the Ubuntu forums at: Grub 2 Password Protection and in the links at the bottom of this post.

    Grub 2 currently supports unencrypted password protection. Encrypted password protection using PBKDF2, as well as password scripting, is currently under development.

    Some of the major points regarding Grub 2 password protection:

    • Grub 2 has the ability to set password protection on individual menuentries and/or for specific users. Examples: Password protect Windows Recovery; prevent user2 from opening the Recovery mode.
    • If password protection is enabled, the superuser username and password are required to gain access to the Grub 2 command line and menu editing modes.
    • The username and/or password do not have to be the same as the Ubuntu logon name/password.
    • This is basic password security. The name/password are unencrypted; anyone having physical access to the machine and more than an elementary knowledge of how Linux works will be able to access the configuration files and bypass this feature.
    • Grub 2 password protection is still being developed. Encryption is available in experimental versions only. If password protection is used, recheck your scripts for changes whenever a new Grub 2 update is released. In 1.97~beta4, passwords must be assigned to each desired menu item. In Lucid Lynx, expect Grub 1.97 to password protect the entire Grub 2 menu if a superuser is designated.
  11. How to Boot to the Recovery Mode w/o a Menu Option
    1. If you have Grub 2 set to boot without displaying the menu at all, hold the SHIFT key down until the menu displays. (In Grub it was the ESC key.)
    2. Press any key once the menu is displayed to ‘freeze’ it. Then arrow to the kernel you want to boot.
    3. Press «e»
    4. Scroll to the end of the «linux /boot/vmlinuz….» line. If displayed, remove «quiet» and/or «splash». Add the word «single» to the end of the line.
    5. Press CTRL-X to boot to the Recovery menu.
  12. Uninstalling GRUB 2
    The command line produces a cleaner uninstall and reinstallation. While adding and removing the packages can be accomplished with Synaptic, certain steps must be accomplished in a terminal.

    • Open a terminal: Applications, Accessories, Terminal.
    • Make backup copies of the main GRUB 2 folders & files
      • Code:
        sudo cp /etc/default/grub /etc/default/grub.old
        sudo cp -R /etc/grub.d /etc/grub.d.old
        sudo cp -R /boot/grub /boot/grub.old
    • Remove GRUB 2
      • Ensure you have an Internet connection and reliable power source. An interruption of either could leave your system in an unbootable condition.
      • Code:
        sudo apt-get purge grub-common grub-pc
      • The user will be warned the system will be unbootable without installing another bootloader.
      • Once the packages are removed, many files will still remain in ‘/boot/grub’
    • Install GRUB 2
      • Code:
        sudo apt-get install grub-common grub-pc
        • The user will be asked for any special commands to add to the default «linux» line. If you aren’t sure, leave it blank, press the TAB key to highlight «OK» and press ENTER.
        • Select the appropriate drive on which to install Grub2 (sda, sdb, etc) by highlighting the entry and pressing the space bar. Normally a partition (sda1, etc) should not be selected.
      • Code:
        sudo update-grub
      • Reboot
  13. Reinstalling GRUB 2 from LiveCD
    If you cannot boot from GRUB 2 and need to reinstall it, here is the simple method. For more details or for advanced options, refer to the Ubuntu community documentation here: Grub2 — Reinstalling GRUB 2:

    • Boot the Ubuntu Live CD (Try without installing).
    • From the Desktop, open a terminal — Applications, Accessories, Terminal.
    • Determine your normal system partition — `sudo fdisk -l` (That is a lowercase L)
    • If you aren’t sure, run `df -Th`. Look for the correct disk size and ext3 or ext4 format.
    • Mount your normal system partition:
      Code:
      sudo mount /dev/sdXY /mnt
      • If you aren’t sure if you mounted the correct partition, once it’s mounted run «nautilus /mnt» to inspect the partition. If it is the correct partition, you should see the normal Ubuntu folders such as /bin, /boot, /etc, /home, etc
      • Example: sudo mount /dev/sda1 /mnt
      • Note: The partition to mount is normally the partition on which Ubuntu was installed: sda1, sdb5, etc. If you have a separate /boot partition, use the device on which the /boot partition is located. Grub 2 works best when installed in the MBR of the drive to which BIOS boots. Also remember that you mount the partition (including the number) in this step, but you do not include the partition number when you run the «sudo grub-install» command later.
      • Note: GRUB 2 counts the first drive (X) as «0», but the first partition (Y) as «1»
    • Only if you have a separate boot partition:
      • Code:
        sudo mount /dev/sdXY /mnt/boot

        with sdXY being your /boot partition designation.

    • Reinstall GRUB 2:
      Code:
      sudo grub-install --root-directory=/mnt /dev/sdX

      Do NOT include the partition number.

      • Example: sudo grub-install —root-directory=/mnt /dev/sda
      • Note: Substitute the device on which Ubuntu was installed — sda, sdb, etc. Do not specify a partition number.
    • Unmount the partition *:
      Code:
      sudo umount /mnt
      • * Note: If you mounted a separate /boot partition, unmount it first:
        Code:
        sudo umount /mnt/boot
    • Reboot.
  14. Booting LiveCD and Other ISOs
    Grub 2 provides the capability to boot certain .iso images. These image files (ISO’s) include the Ubuntu LiveCDsSystemrescueCD and the Parted Magic CD.See the following thread in the Tutorials section for information and instructions on how to boot Ubuntu and other system ISOs:
    ISO Booting with Grub 2
  15. Booting from the Rescue Mode
    One of the improvements of Grub 2 is the ability to recover from a failed boot from the Grub 2 «grub rescue>» or «grub>» prompt. For a detailed discussion and instructions on booting from the Grub 2 prompt, please refer to this tutorial:
    HOWTO: Boot & Install Ubuntu from the Grub Rescue PromptAdditional information on the rescue mode is available in the «Command Line & Rescue Mode« section of the Ubuntu Grub 2 community doc.
  16. Restoring GRUB2 / XP / Vista / Win 7 Bootloaders
    talsemgeest has written an excellent guide on how to restore the bootloaders of various operating systems following the installation of another one. Make sure you reference the section for «9.10 and Beyond», which is for GRUB 2.Rather than duplicate his efforts in this post, here is the link to the original:
    http://ubuntuforums.org/showthread.php?t=1014708

    Restoring Windows MBR without a Windows CD
    If you want to boot directly to Windows but Grub has overwritten the MBR, the normal procdeure is to use the Windows CD to restore things. If you do not have access to the Windows CD, the following commands will rewrite the MBR, removing Grub and allowing the system to boot directly into Windows.

    Boot the Ubuntu LiveCD, open a terminal (Applications, Accessories, Terminal) and enter the following commands. Make sure you correctly identify the Windows device (normally sda):

    Code:
    sudo apt-get install lilo
    sudo lilo -M /dev/sda mbr

    Bonus Section: BSD Menuentry — If you need to have an entry to boot into BSD/Windows from the Grub2 menu, here is the menuentry to put into a custom file:

    Quote:
    menuentry «FreeBSD» {
    insmod ufs2
    set root=(hd1,1)
    chainloader +1
    }
  17. Grub Rescue Image
    A bootable Grub 2 rescue image is available for both floppies and CDs. To obtain the images, install «grub-rescue-pc». Once installed, three images are available in /usr/lib/grub-mkrescue. Use the I]grub-mkrescue [/I] command to create the rescue ISO. See the MAN page for more information. Note: A customized rescue ISO only uses the current systems Grub 2 /boot/grub files. No information from /etc/grub.d or /etc/default/grub is imported.The ISO only boots to the grub prompt. It uses the Grub 2 files found on the ISO; if the problem is with the system’s Grub 2 files the rescue ISO should boot. However, the ISO contains no kernels and must be told where to find the correct kernel and initrd files on the system. The user must know the drive/partition on which the boot files are located and the non-Grub files must exist and be uncorrupted.

    If the user hasn’t made a rescue floppy/ISO, other alternatives include the Ubuntu Installation/LiveCD or SuperGrub Disk.

    • grub-rescue-floppy.img — For floppy images.
      • To Install:
      • Insert a disk in the floppy drive.
      • Code:
        fdformat /dev/fd0
        mkfs -t msdos /dev/fd0
        dd if=/usr/lib/grub-rescue/grub-rescue-floppy.img of=/dev/fd0
    • grub-rescue-cdrom.iso — When burning the image to a CD, select the option to copy an image and not the files.
      • Generate the image using the following command:
        • Code:
          grub-mkrescue --output=<path/filename>
      • If an error message «/usr/bin/grub-mkrescue: 324: xorriso: not found», install the xorriso package and rerun the command.
      • Copy the ISO image to a CD using the CD burning app of your choice.

    Once the grub rescue floppy/CD boots to the grub prompt, run the following commands.

    The commands are slightly different than those used for booting by other means. The Grub 2 files on the floppy/CD are used, and only the kernel and initrd.img files need to be loaded.

    Command line tips:

    • Drives start counting at 0 (sda=0, sdb=1, etc). Partitions start counting at 1 (1=1, etc). Substitute the correct drive letter for X, correct number for Y, and substitute the correct numbers for (hd0,1).
    • You must type the entire path and kernel and initrd names if (hdX,Y)/vmlinuz and (hdX,Y)/initrd.img do not exist. You can check by running this command:
      • ls (hdX,Y)/

      If vmlinuz and initrd.img do not exist at (hdX,Y)/, you can simplify the typing using the TAB complete feature.

    • On the linux line, type «vml» and then TAB to help complete the kernel number. Ensure the complete kernel name is entered. Be sure to fill the kernel number completely, and don’t forget the «root=» and «ro» sections of the linux line.
    • On the initrd line, type «ini» and TAB to fill in a large part of the name. Continue typing/TABBING to ensure the complete .img name is used.
    • Sections in bold should be changed to match the user’s system.
    Code:
    set root=(hd0,1)
    linux (hdX,Y)/vmlinuz root=/dev/sdXY ro
    # or if (hdX,Y)/vmlinuz does not exist:
    linux (hdX,Y)/boot/vmlinuz-2.6.32.25-generic root=/dev/sdXY ro
    # then
    initrd (hdX,Y)/boot/initrd.img 
    # or if (hdX,Y)/initrd.img does not exist:
    initrd (hdX,Y)/boot/initrd.img-2.6.33-25-generic 
    boot
  18. Grub 2 Fallback
    There is a little-documented ‘fallback’ capability which allows Grub 2 to select an alternate menuentry should the default entry fail. Since Grub 2/Natty uses submenus which may alter the way to use fallback, this section covers Grub 1.98/Maverick & earlier.To designate a fallback menuentry, add the following to /etc/grub.d/40_customX is the menuentry number (start counting the grub.cfg menuentries at 0):

    Quote:
    set fallback=X

    Notes regarding the Grub 2 Fallback Option:

    • In Maverick, using the title rather than the menuentry number does not appear to work in /etc/grub.d/40_custom
    • The title can be used if set fallback=»<title>» is placed in /boot/grub/grub.cfg, but is not recommended as it will be removed during updates.
    • Instructions for using the fallback option in Natty/Grub 1.99 will be added once Natty is officially released.
  19. Selected Problems & Bugs «out of disk» ,»device not found», «no such device» , «root device» Errors
    Causes are many, but can be caused by Grub2 not finding partitions/files it is looking for. Some possible areas to explore while troubleshooting:

    • Does your BIOS see the files? Older BIOS may not see past 8GB or 137GB of the partition. You may need to create a separate /boot partition or adjust the BIOS to use the ‘large disk’ mode or update the BIOS to allow it to use today’s larger disks.
    • Some users may need to add «rootdelay=90» to the end of the «linux» line in /etc/default/grub. The might be necessary if the system takes a long time to recognize the drive.
    • The BIOS controller mode may need to be changed. Change the BIOS entry for the SATA Controller from from AHCI to Compatibility mode.

    Lubuntu Dual Booters — No Windows Menu
    Lubuntu apparently doesn’t ship with the package os-prober so Windows will not be added to the Grub 2 menu. To add Windows, install os-prober, update grub and then check to see if Windows is now in the menu:

    Code:
    sudo apt-get install os-prober
    sudo update-grub
    grep menuentry /boot/grub/grub.cfg

    http://www.gnu.org/software/grub/manual/

    Grub Update results in «No Such Disk»:
    A late July 2010 Grub 2 update is causing a «no such disk» error for some users of WUBI, resulting in an unbootable system. If the system doesn’t display the original Windows menu, the most likely cause of the failure is that Grub 2 was installed in the MBR and/or on the Windows partition. To correct this, restore the Windows bootloader using this link:
    How to restore the Ubuntu/XP/Vista/7 bootloader

    Whether the failure is due to improper user selections or Grub 2’s failure to recognize a Wubi install, it has been reported in the following bug and users can review it for status updates and recovery options when they become available:
    https://bugs.launchpad.net/wubi/+bug/610898

    «Fix Symbol ‘grub-puts’ Not Found» Error Message:
    http://www.webupd8.org/2010/05/fix-symbol-grubputs-not-found-when.html
    If you can get to a normal installation, run the grub-install command or use the «dpkg-reconfigure grub-pc» command to put Grub onto your current partition. If you have to use the Live CD, use chroot to run these commands (see chroot link in my signature line.

    Note: Most of this information has been incorporated, with a few graphics, into a page in the Ubuntu Help site. I will try to keep this post up-to-date and users are free to continue to post comments here. The help page is located here:https://help.ubuntu.com/community/Grub2

    meierfra has been busily building pages which detail how to solve many of the common problems users are experiencing with Grub 2. His SourceForge web page should be one of the first stops for those seeking answers to Grub 2 issues.

    Wubi (Windows Ubuntu) Users — wubildr
    Grub2 updates in the spring of 2010 triggered a bug in the ntfs module causing Wubi boot failures. The solution to this boot problem was posted by Agostino Russo and is found in this Lucid Lynx LaunchPad Bug Report #477169, Post 210. The module causing the errors has been fixed and replacing the «wubildr» file in Windows permanently solves this problem. meierfra has kindly provided clear instructions on how to fix this problem athttp://sourceforge.net/apps/mediawiki/bootinfoscript/index.php?title=Boot_Problems:Wubi_9.10

    Lose Ubuntu/Windows After Installing the Other
    If you have lost the ability to boot into Windows or Ubuntu following the installation/reinstallation of the other OS it could be an overwritten MBR issue. If the OS was previously working, there is an excellent guide written by talsemgeest that may very well restore the lost OS. Here is the link:
    How to restore the Ubuntu/XP/Vista/7 bootloader (Updated for Ubuntu 9.10)

    No Menu On Initial Boot
    If you are already on the Ubuntu Desktop, run «sudo update-grub». This may detect additional operating systems, which may allow the Grub menu to be displayed on the next boot. Otherwise:
    Open /etc/default/grub:

    Code:
    gksu gedit /etc/default/grub

    Disable the «GRUB_HIDDEN_TIMEOUT=» line by placing a # symbol at the beginning of the line.
    Set «GRUB_TIMEOUT=» to a positive integer (number of seconds to display the menu before automatic selection) or «-1» to wait for the user to press ENTER (no timeout). The entry will look like this:

    Quote:
    #GRUB_HIDDEN_TIMEOUT=0
    GRUB_HIDDEN_TIMEOUT_QUIET=true
    GRUB_TIMEOUT=»10«

    Save the file, update grub («sudo update-grub») and reboot.

    External Drive Installs and MBR — Bug bug/414996
    When installing Ubuntu to a USB drive, the potential exists for GRUB 2 to write to the hard drive’s MBR or split the installation between the hard drive and the USB drive (rather than completely on the USB device). This can render the main drive unbootable.

    Workaround: During the final stages of the install there is an «Advanced» button which allows the user to select the install location.

    HP Machines Fails to Load Grub after Using Windows — Bug bug/441941
    After installing Grub 2 on a HP machine, the system boots normally until the first time it’s booted into Windows. On the next boot, the system hangs at «Grub loading».

    Workaround: HP protection tools are rewriting to the MBR when Windows is run. The protecttools app must be removed/disabled. Refer to post #10 in the Bug Report.

    «Grub loading. The symbol ‘ ‘ not found. Aborted.» on Dell machines..
    On Dell computers with Dell DataSafe Local Backup (DDSLB) installed, the above message is displayed with a series of characters within the ‘ ‘ section. This is a reported bug,
    bug #482757. Thanks to merry_meercat’s post which details how to fix the problem.

    «error: the symbol `grub_xputs` not found».
    Use the Live CD to chroot into your Ubuntu partition and purge/reinstall Grub2. See post #5 here:
    http://ubuntuforums.org/showpost.php?p=9836539&postcount=5.

    «error: unknown filesystem» on old motherboard & BIOS.
    If you are using an older motherboard/BIOS, make sure the BIOS and system can read your hard drive. There is a 137GB limit in old BIOS settings that prevents the system from recognizing data placed ‘deeper’ into the partition. Try creating a /boot partition smaller than 130GB and see if the system now recognizes it. You can also check to see if there is a BIOS update which may eliminate this problem.

    Grub «error: out of disk» or «failed to boot default entries».
    This error message is sometimes generated when Grub 2 cannot properly write to the file /boot/grub/grubenv. Refer to meierfra’sBoot_Problems:Write page.

    «Grub loading. The symbol ‘ ‘ not found. Aborted.» on Dell machines..
    On Dell computers with Dell DataSafe Local Backup (DDSLB) installed, the above message is displayed with a series of characters within the ‘ ‘ section. This is a reported bug,
    bug #482757. Thanks to merry_meercat’s post which details how to fix the problem.

  20. Links
    Grub 2 (help.ubuntu.com)
    Grub 2: Title Tweaks
    Grub 2: 5 Common Tasks
    Grub 2: Introduction
    Grub 2: Purge & Reinstall
    Grub 2: ISO Booting with Grub 2
    Grub 2: Password ProtectionWubi Megathread by Rubi1200
    Grub 2: A Guide for Users (from Kubuntu
    Forums)

    https://wiki.ubuntu.com/KernelTeam/Grub2Testing
    ‘Official’ GNU Grub 2 Manual
    GNU Grub 2 Manual/Wiki (in development)
    Grub 2 Wiki
    Herman’s Grub 2 Site Comprehensive.
    Herman’s Grub 2 Scripts Useful scripts for many Grub 2 tasks.
    How to restore the Ubuntu/XP/Vista/7 bootloader
    http://grub.gibibit.com/ Grub 2 Theming (currently for Ubuntu G2 experimental)
    How to restore the Ubuntu/XP/Vista/7 bootloader
    http://sourceforge.net/apps/mediawik…itle=Main_Pagemeierfra’s Grub 2 Solutions Page
    How-to Install 9.10 karmic on fakeraid by gilson585
    How to create a Grub 2 Floppy See post 283 of this thread. Thank you peter b
    Customizing the graphics in Grub See post 283 of this thread. Thank you peter b
    MultiBootUSB Script to install multiple OS’s on thumb/USB drives. Thanks sundar_ima
    How to: Create a Customized GRUB2 Screen that is Maintenance Free Thanks Cavsfan

Взято отсюда: http://ubuntuforums.org/showthread.php?t=1195275

Asterisk on Debian Squeeze

First some background: I use Asterisk to route my calls through multiple VoIP providers. Calls to Australian landlines through iiNet since they’re free, and the rest through Pennytel since they’re cheap. My el-cheapo ATA simply registers with Asterisk and my mum just calls as usual, and everything’s automagically cost optimised.

Problem: I did an apt-get -y dist-upgrade after not having touched this system for quite a while, and one of Asterisk’s dependencies, dahdi, failed to install with the error message FATAL: Module dahdi not found.

Basically, the dependecies don’t cause automatic installation of the needed kernel drivers, so the following will fix it:

apt-get -y install linux-headers-`uname -r` build-essential
apt-get -y remove dahdi*
apt-get -y install dahdi-source
cd /usr/src
tar jxvf dahdi.tar.bz2
cd modules/dahdi
make
make install
apt-get -y asterisk

source: http://cryptwizard.info/?p=691

Asterisk – храним CDR в БД MySQL

Должны быть установлены следующие компоненты:

— Mysql Server 5 and Client
— asterisk-1.4.22
— asterisk-addons-1.4.7

#Скачиваем Asterisk-addons с Digium:

 

1
2
3
4
5
6
cd /usr/src
wget <a title="http://downloads.digium.com/pub/asterisk/releases/asterisk-addons-1.4.7.tar.gz" href="http://downloads.digium.com/pub/asterisk/releases/asterisk-addons-1.4.7.tar.gz">http://downloads.digium.com/pub/asterisk/releases/asterisk-addons-1.4.7....</a>
tar xvfz asterisk-addons-1.4.7.tar.gz
cd asterisk-addons-1.4.7/cdr/
vi cdr_addon_mysql.c
add #define MYSQL_LOGUNIQUEID after #define DATE_FORMAT “%Y-%m-%d  %T”

 

1
2
3
cd ..
./configure
make menuselect

Проверяем, загружен ли модуль:

1
2
3
4
5
6
7
8
9
10
11
—> 1. Applications
[*] 1. app_addon_sql_mysql
2. Call Detail Recording
[*] 1. cdr_addon_mysql
3. Channel Drivers
4. Format Interpreters
5. Resource Mod
then q (quit) and S (save)
make && make install

Редактируем файл /etc/asterisk/cdr.conf

1
2
3
4
vi /etc/asterisk/cdr.conf
[general]
enable=yes

Редактируем файл /etc/asterisk/cdr_mysql.conf

1
2
3
4
5
6
7
8
9
[global]
hostname=localhost
dbname=asterisk
table=cdr
password=pass01234
user=asterisk
port=3306
;sock=/tmp/mysql.sock
;userfield=1

Редактируем файл /etc/asterisk/modules.conf

1
vi /etc/asterisk/modules.conf

добавляем следующие строки (если нет):

1
load => cdr_addon_mysql.so

Создаем БД, таблицы и разрешения.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
ipbbx01:~# mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or g.
Your MySQL connection id is 2
Server version: 5.0.32-Debian_7etch5 Debian etch distribution
Type ‘help;’ or ‘h’ for help. Type ‘c’ to clear the buffer.
mysql> create database asterisk;
mysql> use asterisk;
mysql> CREATE TABLE cdr (
calldate datetime NOT NULL default ‘0000-00-00 00:00:00′,
clid varchar(80) NOT NULL default ”,
src varchar(80) NOT NULL default ”,
dst varchar(80) NOT NULL default ”,
dcontext varchar(80) NOT NULL default ”,
channel varchar(80) NOT NULL default ”,
dstchannel varchar(80) NOT NULL default ”,
lastapp varchar(80) NOT NULL default ”,
lastdata varchar(80) NOT NULL default ”,
duration int(11) NOT NULL default ‘0′,
billsec int(11) NOT NULL default ‘0′,
disposition varchar(45) NOT NULL default ”,
amaflags int(11) NOT NULL default ‘0′,
accountcode varchar(20) NOT NULL default ”,
userfield varchar(255) NOT NULL default ”,
uniqueid varchar(32) NOT NULL default ”
);
ALTER TABLE cdr ADD INDEX ( calldate );
ALTER TABLE cdr ADD INDEX ( dst );
ALTER TABLE cdr ADD INDEX ( uniqueid );
You can add more indices if you want.
mysql> q
[/mysql]
Не забываем дать разрешения пользователю asterisk@localhost для  работы с БД MySQL:
[mysql]
mysql> GRANT SELECT,INSERT,UPDATE,DELETE,CREATE,DROP
-> on asterisk.*
-> to 'asterisk'@'localhost';
Query OK, 0 rows affected (0.00 sec)

Проверяем соединение:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ipbx01:~# mysql -h localhost -u asterisk -p asteriskmysql> show tables;
+——————–+
| Tables_in_asterisk |
+——————–+
| cdr |
+——————–+
1 row in set (0.00 sec)
mysql> desc cdr;
+————-+————–+——+—–+———————+——-+
| Field | Type | Null | Key | Default | Extra |
+————-+————–+——+—–+———————+——-+
| calldate | datetime | NO | MUL | 0000-00-00 00:00:00 | |
| clid | varchar(80) | NO | | | |
| src | varchar(80) | NO | | | |
| dst | varchar(80) | NO | MUL | | |
| dcontext | varchar(80) | NO | | | |
| channel | varchar(80) | NO | | | |
| dstchannel | varchar(80) | NO | | | |
| lastapp | varchar(80) | NO | | | |
| lastdata | varchar(80) | NO | | | |
| duration | int(11) | NO | | 0 | |
| billsec | int(11) | NO | | 0 | |
| disposition | varchar(45) | NO | | | |
| amaflags | int(11) | NO | | 0 | |
| accountcode | varchar(20) | NO | | | |
| userfield | varchar(255) | NO | | | |
| uniqueid | varchar(32) | NO | MUL | | |
+————-+————–+——+—–+———————+——-+
16 rows in set (0.00 sec)
mysql>

Данный этап завершен! Теперь проверяем, загружен ли mysql модуль.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
ippbx01# asterisk -r
Asterisk 1.4.20, Copyright (C) 1999 - 2008 Digium, Inc. and others.
Created by Mark Spencer
Asterisk comes with ABSOLUTELY NO WARRANTY; type ‘core show  warranty’ for details.
This is free software, with components licensed under the GNU  General Public
License version 2 and other licenses; you are welcome to  redistribute it under
certain conditions. Type ‘core show license’ for details.
=========================================================================
Connected to Asterisk 1.4.20 currently running on asterisk88 (pid =  26648)
Verbosity is at least 3
ippbx01*CLI> stop now
ippbx01*CLI>
Disconnected from Asterisk server
ippbx01# safe_asterisk
ippbx01# asterisk -r
Asterisk 1.4.20, Copyright (C) 1999 - 2008 Digium, Inc. and others.
Created by Mark Spencer
Asterisk comes with ABSOLUTELY NO WARRANTY; type ‘core show  warranty’ for details.
This is free software, with components licensed under the GNU  General Public
License version 2 and other licenses; you are welcome to  redistribute it under
certain conditions. Type ‘core show license’ for details.
=========================================================================
Connected to Asterisk 1.4.20 currently running on asterisk88 (pid =  26880)
Verbosity is at least 3
ippbx01*CLI> cdr mysql status
<h2>Connected to asterisk@localhost, port 3306 using table cdr for 15  seconds.</h2>
Wrote 0 records since last restart.
ippbx01*CLI> quit

Вот и все, хранение CDR в БД MySQl у нас работает.

 

Recompile SoX on Debian

know this thread is ancient, but it’s the one I came across when googling for an answer, so I thought I’d post my solution here.

You can recompile sox with mp3 encoding support. First, ensure that multiverse, universe and restricted are in your /etc/apt/sources.list. Then install the necessary software and libraries:

Code:
sudo aptitude install sox build-essentials liblame liblame-dev

You need to install liblame and liblame-dev as they are not dependencies of sox and so won’t get installed automatically at the build-dep stage. I put sox in there so as to ensure that all the other non-lame run-time library dependencies for sox get installed before we build and install our new version.

Change directory to a nice place (I like /usr/src), then get the source for sox and the libraries on which it depends:

Code:
sudo apt-get build-dep sox
Code:
sudo apt-get source sox

Unpack the source:

Code:
sudo dpkg-source -x sox_12.18.2-1.dsc

Edit the debian/rules file with your favourite editor:

Code:
sudo vim sox-12.18.2/debian/rules

and comment out, by putting an ‘#’ at the beginning of the line, the two lines that read:

Quote:
DEB_CONFIGURE_EXTRA_FLAGS := —disable-lame

Change directory into the sox source directory

Code:
cd sox-12.18.2

and build the binary deb:

Code:
sudo dpkg-buildpackage -b

Change directory up one level and install the newly built mp3 encoding sox .deb:

Code:
sudo dpkg -i sox_12.18.2-1_i386.deb

And you are done…

 

Convert audio between MP3, FLAC, WAV — including hi-fi and lo-fi and short clips

Using SoxLAMEFLAC, and madplay — I put together this “dictionary” of shell commands that can be run to convert audio from one format to other, including dialup-modem-streamable lofi mono MP3 files, and including shorter clips of music.

Above each command-line and the INPUT and OUTPUT audio formats. (represented by $in and $out in the command line.)

For short audio clips, you need $start — what second to start the clip at, and $duration — how long the clip should go. All clips have a 1-second fade-in, and 2-second fade-out.

flac wav
flac -sd $in -o $out

flac wav clip
flac -sdc $in | sox -t wav — -t raw -s -w -c 2 — trim $start $duration | sox -t raw -r 44100 -s -w -c 2 — $out fade h 1 $duration 2

flac wav-lofi
flac -sdc $in | sox -t wav — -s -w -c 1 -r 22050 $out rate

flac mp3-hifi
flac -sdc $in | lame — $out

flac mp3-hifi clip
flac -sdc $in | sox -t wav — -t raw -s -w -c 2 — trim $start $duration | sox -t raw -r 44100 -s -w -c 2 — -t wav — fade h 1 $duration 2 | lame — $out

flac mp3-lofi
flac -sdc $in | sox -t wav — -t wav -s -w -c 1 -r 22050 — rate | lame -b 80 — $out

flac mp3-lofi clip
flac -sdc $in | sox -t wav — -t raw -s -w -c 1 -r 22050 — rate | sox -t raw -r 22050 -s -w -c 1 — -t raw -r 22050 -s -w -c 1 — trim $start $duration | sox -t raw -r 22050 -s -w -c 1 — -t wav — fade h 1 $duration 2 | lame -b 80 — $out

wav flac
flac -s $in -o $out

wav wav clip
sox -t wav $in -t raw -s -w -c 2 — trim $start $duration | sox -t raw -r 44100 -s -w -c 2 — -t wav $out fade h 1 $duration 2

wav wav lofi
sox -t wav $in -s -w -c 1 -r 22050 $out rate

wav mp3-hifi
lame $in $out

wav mp3-hifi clip
sox -t wav $in -t raw -s -w -c 2 — trim $start $duration | sox -t raw -r 44100 -s -w -c 2 — -t wav — fade h 1 $duration 2 | lame — $out

wav mp3-lofi
sox -t wav $in -t wav -s -w -c 1 -r 22050 — rate | lame -b 80 — $out

wav mp3-lofi clip
sox -t wav $in -t raw -s -w -c 1 -r 22050 — rate | sox -t raw -r 22050 -s -w -c 1 — -t raw -r 22050 -s -w -c 1 — trim $start $duration | sox -t raw -r 22050 -s -w -c 1 — -t wav — fade h 1 $duration 2 | lame -b 80 — $out

mp3 flac
madplay -q -o wave:- $in | flac -s — -o $out

mp3 wav clip
madplay -q -o wave:- $in | sox -t wav — -t raw -s -w -c 2 — trim $start $duration | sox -t raw -r 44100 -s -w -c 2 — $out fade h 1 $duration 2

mp3 wav lofi
madplay -q -o wave:$out -m -R 22050 $in

mp3 mp3-hifi
cp $in $out

mp3 mp3-hifi clip
madplay -q -o wave:- $in | sox -t wav — -t raw -s -w -c 2 — trim $start $duration | sox -t raw -r 44100 -s -w -c 2 — -t wav — fade h 1 $duration 2 | lame — $out

mp3 mp3-lofi
madplay -q -o wave:- -m -R 22050 $in | lame -b 80 — $out

mp3 mp3-lofi clip
madplay -q -o wave:- -m -R 22050 $in | sox -t raw -r 22050 -s -w -c 1 — -t raw -r 22050 -s -w -c 1 — trim $start $duration | sox -t raw -r 22050 -s -w -c 1 — -t wav — fade h 1 $duration 2 | lame -b 80 — $out

Got any more single-line open-source audio-converting commands to add?

—————————————————

Try this one 🙂

ls *.flac |while read a; do n=$(basename «$a» .flac); flac -sdc «$a» |lame -V 1 — «${n}.mp3» ; done

————————————————

just save this into a file
such as convert.sh and make it executable

#!/bin/bash
FILES=$(ls *.flac | cut -d ‘.’ -f1)
for i in $FILES; do
echo converting: $i.flac
flac -sdc $i.flac | lame — $i.mp3
done

—————————————-

 

Windows Subversion/TortoiseSVN: сравнение и экспорт изменений между двумя ревизиями

Зачем это может понадобиться? Да очень просто, чтобы получить файлы, которые изменились между двумя версиями в репозитории Subversion. Оказывается в Subversion нет такой команды, чтобы получить эти самые файлы. Можно сделать export конкретной ревизии, но в любом случае получим все файлы на тот период. Но не все так плохо. Оказывается можно добиться необходимого результата с помощью отличной программы TortoiseSVN – клиент для Subversion. Очень полезный и удобный инструмент, рекомендую.

Чтобы получить список файлов, которые изменились, делаем следующее:
• Выбираем две резизии (Рисунок №1), только две, с большим количеством не сработает
• Над одной из выбранных ревизий, вызываем контекстное меню (правой кнопкой), появляется менюшка (Рисунок №2), где нажимаем на пункт «Compare revision»
• В результате получаем следующее окно (Рисунок №3), где выбираем все файлы (можно через комбинацию клавиш Ctrl+A), вызываем контекстное меню и нажимаем «Export selection to …» – Рисунок №4.
• Указываем куда хотим сохранить выбранные файлы.

При таком экспорте сохраняется вся структура папок. В итоге получаем очень удобную функциональность.

Рисунок №1: Окно ревизий «Log Messages»

Рисунок №2: Контекстное меню – вызываем команду «Compare revision»

Рисунок №3: Список изменений между двумя ревизиями

Рисунок №4: Контекстное меню – выбираем место куда сохранить файлы

Ссылки по теме:
TortoiseSVN docs: Revision Log Dialog
Windows SubVersion / TortoiseSVN – Compare two versions of a file
TortoiseMerge and TortoiseDiff – viewing differences
Using TortoiseSVN (tutorial)

Инструменты обеспечение качества программного продукта для PHP

В тексте статьи находится краткий обзор инструментов с помощью которых можно анализировать различные характиристики в приложениях созданных на PHP. Данный материал появился на свет в результате некоторых экспериментов в области непрерывной интеграции, и должен был являться частью статьи про непрерывную интеграцию (спойлерить пока не буду, боюсь сглазить) все в том же РНР, но я решил все-таки выделить его в самостоятельный обзор, так как возможно, в последующих статьях я буду ссылаться на него, а так же надеюсь узнать об аналогичных инструментах еще не попавших мне на глаза. Некоторые инструменты уже были рассмотрены достаточно подробно, но тем не менее полного списка всех доступных еще не было.

PHP_CodeCoverage

PHP_CodeCoverage это библиотека, которая обеспечивает сбор, обработку и отображение информации о покрытии кода тестами, требует xdebug, а так же использует некоторые сторонние библиотеки. Более подробная информация находится на официальном сайте.

Автор: Sebastian Bergmann
Официальный сайт: http://github.com/sebastianbergmann/php-code-coverage
Официальный PEAR канал: http://pear.phpunit.de/
Текущая версия: 0.9.0 (alpha)
PhpDocumentor

На основании комментариев в исходном коде генерирует соответствующую документацию, имеет уйму возможностей в числе которых презентабельный и дружественный к пользователю шаблоны.

Автор: Joshua Eichorn
Официальный сайт: http://www.phpdoc.org/
Официальный PEAR канал: http://pear.php.net/
PHP Copy/Paste Detector [phpcpd]

Название говорит само за себя: находит дублированный код и сообщает о нем.

Автор: Sebastian Bergmann
Официальный сайт: http://github.com/sebastianbergmann/phpcpd
Официальный PEAR канал: http://pear.php.net/
Текущая версия: 1.3.1 (stable)
PHP_Depend

Собирает и отображает статистическую информацию о проекте.

Автор: Manuel Pichler
Официальный сайт: http://pdepend.org/
Официальный PEAR канал: http://pear.pdepend.org/
Текущая версия: 0.9.11 (beta)
PHP_PMD

Ответвление от PHP_Depend: отображает информацию о размерах кода, используемых именах, неиспользуемом коде. Обзор от DevMan

Автор: Manuel Pichler
Официальный сайт: http://phpmd.org/
Официальный PEAR канал: http://pear.phpmd.org/
Текущая версия: 0.2.5 (alpha)
PHP_CodeSniffer

Позволяет наблюдать за состоянием PHP, Javascript и CSS файлов и определять отклонения от принятых стандартов кодирования. Обзор от DevMan

Автор: Greg Sherwood
Официальный сайт: http://matrix.squiz.net/developer/tools/php_cs
Официальный PEAR канал: http://pear.php.net/
Текущая версия: 1.2.2 (stable)
PHPUnit

Пожалуй самый известный инструмент для модульного тестирования, думаю в представлении не нуждается.

Автор: Sebastian Bergmann
Официальный сайт: http://www.phpunit.de/
Официальный PEAR канал: http://pear.phpunit.de/
Текущая версия: 3.4.12 (stable)
PHP_CodeBrowser

Обеспечивает просмотр кода с синтаксической подсветкой, имеет богатые возможности по визуализации, может использовать отчеты от: phpunit, phpcpd, padawan, phpcs. Из этого обзора можно понять насколько инструмент перспективный.

Автор: Mayflower GmbH
Официальный сайт: http://github.com/mayflowergmbh/PHP_CodeBrowser
Официальный PEAR канал: http://pear.phpunit.de/
Текущая версия: 0.1.3 (alpha)
phploc

Еще один инструмент собирающий статистическую информацию о проекте.

Автор: Sebastian Bergmann
Официальный сайт: http://github.com/sebastianbergmann/phploc
Официальный PEAR канал: http://pear.phpunit.de/
Текущая версия: 1.5.1 (stable)
phpdcd

Детектор неиспользуемого кода (Dead Code Detector) для PHP. Он сканирует PHP проект на предмет всех определенных функций и методов и сообщает о них как о неиспользуемых если из вызов не встречается хотя бы однажды

Автор: Sebastian Bergmann
Официальный сайт: http://github.com/sebastianbergmann/phpdcd
Официальный PEAR канал: pear.phpunit.de
Текущая версия: 0.9.2 (beta)
Padawan

Инструмент для обнаружения антипаттернов, обходных путей и прочих неприятностей.

Автор: Sebastian Bergmann
Официальный сайт: http://github.com/sebastianbergmann/padawan
Официальный PEAR канал: неизвестен
Текущая версия: неизвестна
PHP_CachegrindParser

Обработчик для cachegrind файлов создающий xml отчеты для последующего использования в CI.

Автор: Mayflower GmbH
Официальный сайт: http://github.com/mayflowergmbh/PHP_CachegrindParser
Официальный PEAR канал: неизвестен
Текущая версия: неизвестна
Источник статьи
Хабрахабр: PHP – Обеспечение качества программного продукта

Что ещё можно почитать:
http://sebastian-bergmann.de/software/
http://manuel-pichler.de/

MySQL: cравнение даты (datetime) через оператор BETWEEN

Оператор BETWEEN идеально подходит для сравнения диапазона между датами (datetime). Но тут есть подводные камни. Например, есть задача – выбрать данные из таблицы за некоторый промежуток времени (с ’2008-08-14′ по ’2008-08-23′).

Рекомендации:
1. Выполняя любые сравнения, приводить все данные к одному типу.
2. Если один операнд имеет значение типа TIMESTAMP или DATETIME, а другой является константой, операнды сравниваются как значения типа TIMESTAMP. А это значит, что если была строка в виде ’2008-08-14′, то она автоматически преобразуется в TIMESTAMP ’2008-08-14 00:00:00′ и это влияет на результат запроса.
3. Над данными, которые участвуют в условиях сравнения желательно не делать никаких операций – это позволяет для них использовать индексы, иначе они игнорируются.

Примеры запросов с BETWEEN и без него:

# Поле created_at - тип DATETIME
# КОРРЕКТНЫЕ ЗАПРОСЫ

# 1: Индексы для created_at поля не используются.
# Условие BETWEEN '2008-08-14' AND '2008-08-23'
# преобразуется в BETWEEN '2008-08-14 00:00:00' AND '2008-08-23 00:00:00'.
SELECT * FROM news
WHERE DATE(created_at) BETWEEN '2008-08-14' AND '2008-08-23';

# 2: Оператор BETWEEN не используем, но тоже не самый лучший вариант, индексы не используются
SELECT * FROM news
WHERE DATE(created_at) >= '2008-08-14' AND DATE(created_at) <= '2008-08-23'; # 3: Строки '2008-08-14 00:00:00' и '2008-08-23 23:59:59' не приведены к типу данных DATE SELECT * FROM news WHERE created_at BETWEEN '2008-08-14 00:00:00' AND '2008-08-23 23:59:59'; # 4: Самый лучший вариант, привели к типу DATETIME, индексы будут использоваться SELECT * FROM news WHERE created_at BETWEEN STR_TO_DATE('2008-08-14 00:00:00', '%Y-%m-%d %H:%i:%s') AND STR_TO_DATE('2008-08-23 23:59:59', '%Y-%m-%d %H:%i:%s'); ############################# # НЕПРАВИЛЬНЫЕ ЗАПРОСЫ # 5: Строки '2008-08-14' и '2008-08-23' преобразуются в TIMESTAMP и дополняются '00:00:00' SELECT * FROM news WHERE created_at >= '2008-08-14' AND created_at <= '2008-08-23';

 

# 6: Аналогично запросу 5
SELECT * FROM news
WHERE created_at BETWEEN STR_TO_DATE('2008-08-14', '%Y-%m-%d') AND STR_TO_DATE('2008-08-23', '%Y-%m-%d');

Получаем самый лучший запрос:

SELECT * FROM news
WHERE created_at BETWEEN STR_TO_DATE('2008-08-14 00:00:00', '%Y-%m-%d %H:%i:%s')
AND STR_TO_DATE('2008-08-23 23:59:59', '%Y-%m-%d %H:%i:%s');

Ссылки по теме:
MySQL 5.1 Reference Manual :: 11.2.3 Comparison Functions and Operators :: Operator BETWEEN
MySQL 5.1 Reference Manual :: 11 Functions and Operators :: 11.6 Date and Time Functions
Search by Date or Timestamp in MySQL