Linux Command Line
Author: Michael Minn (see www.michaelminn.com for current contact info)
July 11, 2006
An introduction to Linux operation and configuration from the command line interface
The purpose of this document is to provide a quick reference for shell commands that can be used to configure and operate Linux. Although it may have some value as a tutorial, it is intended more as a set of examples of command usage for common tasks that may be forgotten if not performed regularly. This document assumes some UNIX/LINUX knowledge and is oriented around the SuSE 9.0 Linux distribution with bash.
This document references a number of topics that have come up in my own personal use of Linux. As such, it is very spotty and is not intended to be comprehensive.
One of the strengths of UNIX and Unix-like systems is the availability of a standardized and extremely robust command line interface. This interface provides quick access to an extremely wide variety of tasks and permits creation of shell scripts to automate repetitive or complex tasks. Aside from inherently graphical tasks (such as image editing) it is quite possible to operate a Linux almost entirely from a keyboard, thus avoiding the cumbersomeness and carpal-tunnel problems associated with mice.
As Linux usage becomes more widespread, the trend has been toward encouraging the use of more Windoze-like wizards and graphical interfaces to perform tasks formerly performed by editing configuration files and running shell commands. However, for technically inclined "power users" of Linux, the command line is still the fastest and most accurate way to navigate. Graphical interfaces often serve to isolate users from the technical details of the operation of their computers and foster a culture of dependency. Since knowledge is power, ignorance can be undesirable in a world where companies leverage dependency into monopolistic control and technical stagnation.
2. Online Help
The advantage of a GUI is its ability to guide a user through unfamiliar tasks. When working with the command line, that guidance is not present in a graphical interface, but almost all Linux installations include the man utility for displaying manual pages.
man (command): Display manual pages for a command
man -k (keyword): Display a list of manual pages related to a keyword
man -a (keyword): Display all manual pages for a specific command (when there are multiple entries)
Most commands also print some syntax information when invoked with the --help option
3. System Administration
poweroff: Power down the system
reboot: Reboot the system
date: Print date and time from the system clock.
date mmddhhmm: Sets date and time.
date 03221610: sets time to 4:10PM on March 21 (must be superuser)
hwclock: Displays or sets the hardware clock. Changing the hardware clock does not change the system clock. Changing the system clock does not change the hardware clock.
hwclock --set --date="mm/dd/yy hh:mm:ss": sets the hardware clock to the specified date/time
su: Change to superuser login. su (username) can change to any user.
ps: List processes.
ps -A: list all processes, regardless of owner.
top: Continuously refreshing list of processes and resources used
kill: Kill a process
kill (process number). Kill a process by number
kill -9 (process). Sends non-catchable kill signal
killall (program name). Kills all processes with a specific executable name
lsof: List open files by process
hostname: Set the system host name
/etc/HOSTNAME: Configuration file used at boot time containing the system hostname. If you change this, you also need to change the entry for the machine in /etc/hosts so hostname -f works for XFree86. On RedHat machines, this file is /etc/sysconfig/network.
apm: Power management command for older APM machines. Displays current battery status. Suspend and standby usually do not work.
acpi: Power management command for newer ACPI machines. Suspend and standby usually do not work.
lspci: Lists information about devices connected to the internal PCI busses.
lspci -vv: Full dump of information.
hdparm: List and set information about disk drives
hdparm -d 1 /dev/hdc: Turns on direct memory access for the CD-ROM drive. Needed for viewing DVDs on a DVD drive.
chkconfig: List, enable and disable system services
chkconfig --list: List services for current run level
useradd: Add a user. Note that you will also need to use the passwd command to set the initial password so the account is enabled.
useradd -m (username) : Add a user and create a directory for them in /home
passwd (username): Set the password for a user.
userdel: Delete a user.
id: List user and group ID numbers
ldd (program_name): List libraries used by a program
strace (program_name): List system calls used by a running program
whereis (program_name): Find the full file path to a program
whois (domain_name): Find whois database information for a domain name. Requires an internet connection to get to a database server
xterm: Pop up a new X terminal window
4. File Viewing, Editing and Conversion
gimp: Extremely powerful graphic file editor
gqview: image viewer. Good for viewing directories of graphic files
gs: Ghostscript viewer for PDF (.pdf) and Postscript (.ps) files
ps2pdf input_file.ps output_file.pdf: convert postscript (.ps) files (which can be created from the office applications or browsers) to .pdf (Adobe Acrobat) format
sodipodi: A SVG (scaled vector graphics) editor
ooffice: Open Office (Red Hat)
OOo: Open Office (SuSE)
xpdf: View an Adobe Acrobat (tm) PDF file
5. Internet Browsing and E-mail
fetchmail: Command line e-mail client
fetchmail -u <username> -a -p POP3 --bsmtp temp.txt <server>.com: Download e-mail from server to a text file
lynx: Primitive command line web browser
mozilla: The standard browser and e-mail program
w3m: Primitive command line web browser
vi is an old standard command line terminal text editor that has been a part of UNIX for years. It is extremely powerful but also very cryptic. For users that have become accustomed to mouse-based point-and-click editors it is an acquired taste, but once acquired, becomes an addiction.
The usage of vi is well documented elsewhere on the web, so this section will simply include some random tweaks and hints that have been useful to me.
vim: On most distributions, vi is linked to vim, an "improved" version of vi. You can verify this by simply typing vi and viewing the opening screen. Vim is highly preferred over vi.
Modes: vim has four different modes: normal, visual, insert and command-line.
Configuration: vi uses a configuration file in the home directory: /home/(username)/.vimrc. The following are some helpful options.
syntax enable set backspace=2 set autoindent set textwidth=0
Printing: vi can print text files to connected postscript printer devices with the hardcopy command. There are a number of printing options that can be set with the set printoptions command from the command-line (or .vimrc file). The following are some I have found useful (respectively): recognize formfeed characters, use letter-size paper (default is European A4 size) and not print an annoying header with the file name.
Page Breaks: Page breaks for printing can be inserted in the file with the formfeed control character ^L; which can be inserted from insert mode by typing ^V ^L.
There are numerous multimedia playback and creation programs for Linux, all of them with significant flaws and none of them universal. While audio can be played back directly from the command line on any system with OSS or ALSA, video always needs an X windows interface. Regardless, the names of executable files included with Fedora distributions are given here so they can be started directly from the command line.
xmms is a graphical audio file player similar to winamp. It has a playlist window and I find it to be the best no-nonsense player for .wav and mp3 files. To play all mp3 files in a directory
mplayer is a player for many different kinds of media files, including windoze media and realaudio/video and direct play from DVDs. It can also be used for converting from proprietary formats to something you can actually use. There are numerous graphical front-ends to get around the multitude of confusing command-line options, but if you're not doing anything too complex, command-line use is generally straightforward. Use from the command line also allows you to see the error messages, which are helpful in diagnosing inevitable, frequent problems with streaming media.
Links to audio and video streams on web pages are frequently hidden inside scripts or the source of popup windows and may be unavailable when autodetection scripts bump you out of pages because you don't have their preferred proprietary media player installed. For example, clicking on an Amazon.com sound sample will download a file to your home directory called "hurl.exe", which contains a link to the Windoze media sound sample. But provided you can find a link, you can usually stream it with mplayer, pressing ctrl-c to stop when you're done.
Play the streamed Sunday service from NYC's Riverside Church mplayer mms://188.8.131.52/theriversidechurch Convert Windoze media file to .wav file mplayer -ao pcm -aofile output.wav infile.wma
mplayer requires a number of proprietary binary codecs stored in /usr/local/lib/codecs, which is why mplayer has to be hosted in Hungary to avoid the DMCA thought-police. One common misleading mplayer error message often occurs when trying to stream quicktime video:
mplayer http://www.nasa.gov/qtl/151335main_NASA_TV_QT.qtl Win32 LoadLibrary failed to load: avisynth.dll...
Hard as you search, you will not be able to find an avisynth.dll in any of the distributed mplayer codecs However, it is unnecessary, since it is just a playlist handler, which is what many quicktime links point to. You can (sometimes) get past it by using the -playlist option, although you may get another nasty set of error messages:
mplayer -playlist http://www.nasa.gov/qtl/151335main_NASA_TV_QT.qtl rtsp_session: Not a Real server. Server type is 'QTSS-Akamai/5.0.2 (Build/452.2.1; Platform/Linux; Release/Panther; )'. Not a Realmedia rtsp url. Trying standard rtsp protocol. RTSP support requires the "LIVE.COM Streaming Media" libraries! Unable to open URL: rtsp://a1303.l1857048516.c18570.g.lq.akamaistream.net/D/1303/18570/v0001/reflector:48516
mplayer can be recompiled with the live.com streaming media libraries. Instructions are available from live555
VLC: If you prefer a graphical Windoze media player and don't feel like fighting with mplayer, VLC comes in binary packages for most common, contemporary distributions.
cdda2wav: Program for ripping tracks from audio CDs to .wav PCM audio files (which can then be edited or compressed to MP3s)
List audio CD track data cdda2wav -JD /dev/cdrom Rip all tracks from an audio CD cdda2wav -D /dev/cdrom -B Rip track 2 from an audio CD to the file file.wav cdda2wav -D /dev/cdrom -t 2 file.wav
lame: One of the best and most popular MP3 encoders for Linux is LAME. Most distros chose to stay completely out of the MP3 inquisition by not shipping any MP3 capability in their distribution. No matter. More information is available from the LAME website.. Downloads can be made from the L.A.M.E. FTP directory. Compilation is simple - just download the tarball, decompress and make. This creates a single executable file called "lame":
tar -zxvf lame* cd lame* ./configure make install
The numerous options can be displayed with the --help option.
Encode to 128 Kbps mp3 file (medium quality) lame input_file.wav output_file.mp3 Encode with id3 identification tags that players display lame input.wav --tt "song title" --ta "artist" output.mp3 Encode at 1Kbps bitrate (rather than default 128 Kbps). Advised when encoding from sources with alot of high frequency noise (such as cassette or 78's) or to create a higher quality (and larger) MP3 file. lame input.wav -b 256 --tt "In The Mood" output.mp3
sox is a command-line program for manipulating uncompressed audio files in various formats - .aiff, .wav, but not mp3. There are numerous options for changing sample rates and bit-resolution as well as adding effects. sox can also serve as a simple command line player or recorder through the play and record scripts usually included with Fedora. sox normally doesn't issue any messages when there are no errors and the -V (verbose) option is helpful if you want to know for certain what it's doing.
Convert a file in Macintosh AIFF format with uncertain characteristics to a standard (Windoze) 16-bit, 44.1 Khz stereo WAV file sox infile.aiff -r 44100 -w -c 2 outfile.wav Play an audio file play file.wav Record from the default audio device (/dev/dsp) to an audio file. Press ctrl-C to stop recording record file.wav
cdplay: Command line CD player
mp3blaster: Command line MP3 file player
rhyme: is a simple rhyming dictionary that supports about 127,000 words. It supports syllable counting and perfect rhymes. A must for every Linux songwriter. You can download the source here.
realplay: is a graphical RealAudio/Video player available in a Linux version from Real.com. It's ugly and often fails with no meaningful error messages. It also doesn't work with some media files encoded with older versions of their codec, such as the audio samples on Amazon.com. mplayer also plays most RealAudio/Video and is a better option.
realproducer: A Linux version of Helix Producer Basic (formerly RealProducer) is available free from Real Networks for creating Real Media files. While it is a command line encoder and does not have a convenient X-Window interface, it is all you need to create Real Audio files. It also apparently can encode Real Video, but only the Windows version can handle .avi files and I have never tried it with other formats. To install, download the tarball from real.com into a temporary "/home/[username]/realproducer" directory. You need a temporary directory because the tarball does not create a subdirectory when it uncompresses
Decompress the tarball, run the install script and follow the prompts:
$ tar -zxvf realproducer_8.5_linux.tar.gz. $ ./install
Both Real Producer Basic (free) and Real Producer Plus (not free) are included in the tarball, but Real Producer Basic has met all of my needs. A complete list of the extensive command line options can be listed by typing "realproducer --help".
My primary usage of Real Producer has been to create streaming audio from .wav files. The following example creates a real audio file titled "My Song" from the mysong.wav file specifically for 56K modems.
realproducer -i mysong.wav -o mysong.rm -b "My Song" -h "Michael Minn" -c "(c) 2001 by Michael Minn" -t 1 -a 2 -f 0
To stream the audio from a website, you need to create a .ram file that contains one line that is a link to the .rm file. For the above my_song.rm example, if you were posting it to an "audio" directory under www.mysong.com and saved as "my_song.ram":
Links to the audio should then refer to "http://www.mysong.com/audio/mysong.ram"
ogle: DVD Player
8. File System
df: List free disk space
du: List the amount of space used in a particular directory
file: List a file type
stat: List detailed information about a file
find (directory) -name "[file name (with wildcards)]": Find a file in a directory
fdformat: Low level floppy drive formatting
mkdosfs: Create a DOS file system on a device
fdformat /dev/fdo; mkdosfs -cv -F 32 /dev/fd0: format a floppy
ln -s (source) (link_name): create a soft link
dd: Raw device copying utility
dd if=/dev/fd0 of=(filename): Dump a floppy disk image to a file
dd if=(filename) of=/dev/fd0: Create a floppy from a disk image
dd conv=noerror,sync if=/dev/fd0 of=(filename): Dump a bad floppy disk (ignore errors)
Block files: Block devices are used for accessing storage devices like disk drives. Block file names are assigned to block files at boot time.
- For IDE hard drives block files have the form /dev/hdX where X is a letter indicating the drive. /dev/hda is the master drive on the first IDE controller, /dev/hdb is the slave of the first controller, /dev/hdc is the master drive of the second controller, etc.
- The partitions are accessed through separate devices with a partition number following the the block device name, e.g. /dev/hda1 for partition 1 on the first hard drive controller.
- A similar convention is used for SCSI drives, with the form /dev/scX.
mount point: an empty directory that will be used by users to reference a mounted file system.
fdisk: Lists and manipulates partitions on disk drives
fdisk -l /dev/hda: List disk partitions on the primary hard drive
/etc/fstab is a text file that contains mounting parameters. Data is given in six columns that are more or less self-explanatory.
- Device block file name
- Mount point
- File system type
- Mounting parameters
- Dump flag indicating the device should be part of normal backup (1 yes, 0 no)
- Order in which the file system should be checked by fsck when file system integrity check must be performed (1 for root, 2 for other, 0 for no check)
For example: On a dual boot system, the windoze VFAT partition may be the first partition on the first hard drive. Assuming that a directory /windoze has been created as a mount point, the following line will work./dev/hda1 /windoze vfat exec,dev,suid,rw,uid=500,gid=500,umask=0 0 0
The uid and gid should be set to the user that you want to own the partition. You can find a user ID (a three digit number) by typing "id" from a console when logged in as that user.
mount (mount point): mount a file system defined in fstab on a mount point
Mount can also be used with command line options to mount a filesystem not defined in /etc/fstab. The following example mounts an floppy image file (.iso) on the /media/floppy mount point. A "loop" device is needed for mounting an image file as a filesystem.mount -o ro,loop=/dev/loop0 temp.iso /media/floppy
umount (mount point): unmount a file system from a mount point
9. Installation Notes
All significant Linux installation programs include the shell and shell commands in even the most basic installation. You will have to make choices between the desktops (Gnome and KDE) and their associated packages. If you have the available disk space, I would suggest installing everything so you don't have to run back to your install disks to find that one missing program you didn't think you'd need.
Text Login. I prefer to see what's going on with my machine rather than have the boot messages hidden behind a glitzy bitmap. Therefore, I have configured my machine to boot in run level 3 (text mode) rather than run level 5 (X windows mode). As superuser, edit the /etc/inittab file and change the line:
id:5:initdefault: to id:3:initdefault:
If you chose text login mode, you will be given a VGA login prompt when you initially boot Linux. After you login, you type startx to start the X Windows desktop. Be aware that the screen will go completely black for a few seconds while X starts.
mwm. It is nice to run under X Windows so you can use multiple terminal windows and so you can use graphical programs like mozilla and gimp. However, the desktops are superfluous for power users. I have discarded GNOME and KDE completely and use Motif Window Manager. You don't get the Start Menu, but you don't have the associated screen clutter and performance hit either. Create a .xinitrc in your home directory (/home/<username>) and type the following lines. This creates a single terminal window, puts a clock window at the bottom of the screen, sets the "desktop" color to blue and starts the window manager. When you type startx, from the text login, it will start. You can create additional terminal windows from a popup menu when you right-click on the desktop.
xterm & xclock -d -update 1 -geometry +819+710 & xsetroot -solid navy exec mwm
Alternative window mangers include wmaker and twm.
Cron Scripts. Within a few minutes of booting Linux, you may notice a flurry of disk activity. If your system stays on for an extended period of time, you may notice similar activity early in the morning (mine starts at 4:02AM). A program called anacron runs system administration programs on a daily, weekly and monthly basis. The configuration file is /etc/anacrontab runs the script /usr/bin/run-parts, which in turn points to the directories containing other scripts, /etc/cron.daily and /etc/cron.weekly. The files in these directories vary by distribution.
The program that is most disk intensive (and intrusive if it starts while you're doing something important) is updatedb, a program that updates a central database for locate, a file searching tool. I never use locate, so I deleted that script. I believe the same script is slocate.cron on RedHat. Not sure what other programs need this database, so buyer beware.
I also deleted /etc/cron.daily/tetex.cron, which deletes unused TeX fonts (since I never use TeX). However, I left tmpwatch (which cleans out unused files in the /tmp directory), logrotate (which cleans up old system logs) and do_mandb (which updates the database used by man -k and whatis).
Unneeded Services. To improve system performance and enhance security, unneeded services should be turned off. chkconfig lists currently active services and can also be used to turn them off. Below is a list of things I have turned off.
chkconfig kudzu off # Annoying RedHat new hardware detection chkconfig isdn off # ISDN controller chkconfig nscd off # Network authentication (not needed when standalone) chkconfig gpm off # Some kind of mouse server chkconfig sendmail off # Mail utility (not needed for non-server) chkconfig netfs off # Automatically mount network file systems chkconfig ntpd off # Network Time Protocol daemon (not needed when standalone) chkconfig autofs off # Automounter chkconfig rawdevices off # Creates raw devices for Oracle, etc. chkconfig cups off # Printer daemon (not needed if you don't have a printer) chkconfig postfix off # Postfix mail system (not needed for non-server) chkconfig smpppd off # SuSE meta PPP daemon chkconfig fbset off # Framebuffer devices ? chkconfig splash off chkconfig splash_early off chkconfig splash_late off
Three Button Mouse Emulation. If you have a mouse/laptop with only two buttons, you can usually enable three-button emulation which allows you to simulate pressing the middle mouse button by pressing both buttons at the same time (the press event will happen on release). The middle button is used by a number of X applications and can be used to copy/paste text between X terminal windows.
True Type Fonts. X Windows on Linux (XFree86) supports True Type fonts. However, since fonts are under copyright, there are usually only a minimal number of True Type fonts included in a Linux distribution. If you want to be able to use the same True Type fonts you use under Windoze (documents, web browsers, etc), copy the .ttf files to /usr/X11R6/lib/X11/fonts/TTF (RedHat) or /usr/X11R6/lib/X11/fonts/truetype (SuSE). The X font server requires information files in the TrueType font directory. Red Hat includes the programs ttmkfdir and mkfontdir to build the fonts.dir and fonts.scale files:
$ cd /usr/X11R6/lib/X11/fonts/TTF $ ttmkfdir > fonts.scale $ mkfontdir
FYI: Paths to fonts are listed in /etc/X11/fs/config or /etc/X11/XF86Config.
SuSE has it's own utility instead of ttmkfdir
cd /usr/X11R6/lib/X11/fonts/trutype SuSEconfig -module fonts
Exit X Windows (<ctrl><alt><backspace>) and startx again to load the fonts. Some distributions do not integrate the font server with X and you may need to manually kill the font server (xfs) before restarting X.
$ killall xfs $ xfs & $ startx
Although it might be nice to have a separate directory to keep track of your Windoze fonts (e.g. /usr/X11R6/lib/X11/fonts/windoze), the /etc/X11/XF86Config file generated by SuSE's X configuration utility (SAX2) apparently has a fixed set of FONTPATH entries. You can edit XF86Config and add a directory, but it will be overwritten if you ever run sax2 again. /usr/X11/lib/sax/api/data/StaticFontPathList seems to be a list used by sax2, but modifying this file had no effect.
RPMs: Redhat Package Manager (RPM) files are the primary format for distributing pre-configured software on Red Hat systems. There are numerous options and the man page is a bit confusing, but these are some options I use frequently
Install from a package file: rpm -i <package_file>.rpm Searching installed packages rpm -qa | grep name Listing files in a package rpm -qlp <package_file>.rpm
rpm2cpio: RPM files use cpio archives to store files. If you need to extract a single file or group of files from an RPM file but don't want to actually install the package, rpm2cpio and cpio can be used to create a fake file structure in a temporary directory that can then be traversed to reach the desired files.
mkdir temp cp package_file.rpm temp cd temp rpm2cpio package_file.rpm | cpio -i --make-directories --preserve-modification-time
diff: diff can be used to find the differences between two files. For example, patches to source code are often given with the output of the following command
diff -Nru source_file.old source_file.c
10. CD Writing
I use the CD-Writer to perform backups of my /home directory. It can, of course, be used to create any kind of CD, but the following instructions are specific to burning a backup CD for a single directory tree. You can probably put all these commands in a script to simplify CD writing, but I am including explicit commands here for clarity. Because things can go wrong at any step and waste media, you might want to do things explicitly from the console for awhile.
mkisofs: Create the CD image with the mkisofs utility. Supposedly it is possible to pipe the output of mkisofs directly into cdrecord without using an image file. However, every time I tried to do this I got "loss of streaming" errors. (imagefile) is an output file from mkisofs that will be used to burn the CD later. This is an arbitrary name...you can put your image anywhere you like (except the directory you're archiving?) (source_directory) is the root of the directory tree that you want to copy. The -r option sets the permissions of all files to be public readable on the CD and enables RockRidge-extensions. The -J option (MS Joliet extensions) can be used to generate a more Windoze friendly CD, but I have had problems with the option yielding the message "tree sort failed". This will take a few minutes.
mkisofs -r -o (image file) (source directory)
Mount test: For testing you can mount image files as if they were disk partitions. This feature is useful to check that the directory layout and file access permissions of the CD image match your wishes. Once you've tested CD-Writing on your system, this step is unnecessary.
mount -t iso9660 -o ro,loop=/dev/loop0 (image file) /mnt/cdrom
Now you can inspect the files under /mnt/cdrom -- they appear exactly as they were on a real CD. To umount the CD-image:
cdrecord: CD-writers need to be fed with a constant stream of data. The process of writing the CD image to the CD must not be interrupted or a corrupt CD will result. Don't do anything with heavy disk access while writing the CD. Mechanical shock to the writer can also ruin the write. I would reccommend going away and doing something else while the CD is burning...it will take 70 minutes for a full CD.
cdrecord -v dev=0,0,0 -data /home/cdimage
Although writers are usually capable of very high speeds, problems can arise keeping the recorder fed a constant stream of data. You may want to add the option "speed=8" or slower if you get errors similar to the following:
Sense Key: 0x3 Medium Error, Segment 0 Sense Code: 0x0C Qual 0x09 (write error - loss of streaming) Fru 0x0 write track data: error after 2424832 bytes
Audio CD: Recording an audio CD is actually a bit simpler than burning a data CD. If you have your audio files all in one directory in .wav format, the following example will burn them all on separate tracks. Since the list will be in alphabetical order, you will need to determine the order of tracks by appending some kind of alphabetical prefix to the track names (i.e. 01_your_song.wav, 02_my_song.wav, 03_his_song.wav, etc.)
cdrecord -v dev=0,0,0 -pad -audio *.wav
cdrdao: is a command line program for writing CDs in disk-at-once (DAO) mode. CDRECORD on most CD writers will only write in track-at-once mode, turning off the laser between track writes and forcing a 2-second gap between audio tracks (since the stream of pits on the CD stops between tracks). Although this usually does not cause problems, the preferred way to write a CD is disk-at-once as a single stream of pits - to prevent tracking errors and in case you want to send the CD to a duplicator to make bulk copies. CDRDAO provides capability for specifying a number of different parameters for disk writing, including specific timings between tracks, UPC numbers and CD-TEXT (album and track names) for writer drivers that support it.
With this added capability comes additional work in setting up the write. CDRDAO requres a text file that defines what the TOC will look like on the written disk. Although the format for this file is not complicated, it is a bit more work than simply specifying a set of files on the command line, as CDRECORD allows.
The internal CD writer is supported. To write, use the following command. Note that you must be SUPERUSER to write a CD.
cdrdao write --driver generic-mmc --device 0,0,0 toc_file
cdrdao with the read-cd option will also allow you to rip multi-track audio and mixed audio/data CDs to a single image file that can be used to burn new CDs:
cdrdao read-cd --read-raw --datafile data.img --device 0,0,0 --driver generic-mmc-raw toc_file.txt
data.image is the image file and toc_file.txt is a listing of the CD table of contents.
CD-RW: I have had very mixed results trying to record to CD-RWs. CD-R media has become so cheap, the added expense and unreliablity of CD-RW makes them generally unnecessary. cdrecord can erase a CD-RW using the "blank=fast" option to erase the old content. Read the man page to learn more about the other options available to erase a CD-RW.
cdrecord -v -force blank=fast dev=0,0,0
Call us dumb or crazy or whatever you want. But if you can't experience what we feel, then you don't understand why we do this. (TJ Lanning, American skier)