Remember back in the days of college when you were allowed to make one sheet of notes for math exams? Well, think of this as a cheat sheet for you Linux exam. Note that commands that need to be executed as root are prefixed with #>
whereas commands that can be run by any user have the prefix $>
.
System Info
-
check Linux version
$> cat /etc/issue $> lsb_release -a
-
system product name, serial number, and sku number
#> sudo dmidecode -s system-product-name #> sudo dmidecode -s system-serial-number #> sudo dmidecode -s system-sku-number
-
output date for a given unix timestamp
$> date -d @1231597505
Containers
-
start container with X display
$> podman run -it --rm -v $XAUTHORITY:$XAUTHORITY:ro -v /tmp/.X11-unix:/tmp/.X11-unix:ro -e DISPLAY --security-opt label=type:container_runtime_t ubuntu bash
Documentation
-
get examples for command
$> tldr grep
CD/DVD Manipulation
-
show cd-burner/cd-reader devices
$> cdrecord -scanbus
-
show cd device information, including read/write speeds, presence of disk
$> readcd -dev 0,0 -sectors=0-0 -f=/dev/null
-
burn an ISO Image
$> cdrecord -v -eject -dao -dev=1,0 -speed=10 -driveropts=burnfree cdimage.iso
-
copy audio cd (no cdrdao)
$> cdda2wav -vall cddb=0 -D0,0 -B -Owav $> cdrecord -v dev=1,0 -dao -useinfo -text -driveropts=burnfree *.wav
-
copy data cd (no cdrdao)
$> readcd -dev 0,0 -f=cdimage.raw $> cdrecord -v -eject -dao -dev=1,0 -speed=10 -driveropts=burnfree cdimage.raw
-
direct cd copy (cdrdao)
$> cdrdao copy --source-device 0,0,0 --device 0,1,0 -n --buffers 32 --on-the-fly
-
raw device cd copy (cdrecord) risky
$> cdrecord -v dev=1,0 -isosize /dev/cdrom0
-
rip DVD vob file to disk
$> vobcopy -l /dev/dvd
Filesystems / Disks
-
find broken symlinks
$ find -L . -type l
-
include dot files in '*' pattern (for easily moving or copying all files in a directory)
$> shopt -s dotglob
-
match all files including dot files (without setting dotglob shopt)
$> ls .[^.]* *
-
delete all files named "target"
$> find . -name 'target' -delete
-
copy files like rsync (preserve file properties and only update files if source is newer)
$> cp -aRu src dest
-
format a removable device into FAT32
$> mkdosfs -F 32 /dev/sdaX
-
make a bootable cd image (ISO) from bootable floppy image (easy way) note: -b specifies the source file
$> mkisofs -pad -b floppy.img -R -o /tmp/cd.iso /tmp/floppy.img
-
make a bootable cd image (ISO) from a directory (won’t include directory name)
$> mkisofs -J -r -o cd.iso burnme/
-
setting up a disk: format with filesystem, then create a partition (using curses fdisk)
$> mkfs.ext3 -L LABEL /dev/sda; cfdisk
-
create a file with a specified size
$> truncate -s 64m filename
-
list hidden directories sorted by size
$> du -s .[^.]* | sort -rn
-
view S.M.A.R.T. information for ATA or SCSI harddisk
#> smartctl -a /dev/hda
-
run short test on disk using S.M.A.R.T
#> smartctrl -t short /dev/hda
-
view results of S.M.A.R.T disk check
#> smartctl -H -l selftest /dev/hda
-
watch files changing in a directory
$> watch "ls -s"
-
delete files older than 7 days
$> find . -type f -mtime +7 | xargs rm -f
* overwrite your hard disk with random characters
$> dd if=/dev/random of=/dev/sda
-
discover and mount lvm volumes: Accessing Logical Volumns (Ubuntu)
-
perform operation on files with possible space in name; read will read to the end of the line and enclosing the result within quotes escapes the spaces
$> find . -type f |grep .ext$ | while read file do cmd "$file" done
-
find broken symlinks
$> find . -type l | while read i ; do test -e "$i" || ls -l "$i"; done
-
fstab mount for samba/windows share
//hostname/sharename /home/$USER/mount/sharename smbfs users,credentials=/home/$USER/.smb.cnf,uid=$USER,gid=$USER 0 0
-
Create a zip file named foo.zip using the contents of the directory foo excluding any SVN directories
$> zip -r foo.zip foo -x \*.svn/*
Multimedia
-
reencode mp3 to make it smaller without losing quality
$> ffmpeg -i original.mp3 -c:a libmp3lame -q:a 4 reencoded.mp3
-
record realmedia streams to disk with vsound
$> vsound -f output.wav -t realplay test.rm
-
record realmedia streams to disk with mplayer
$> mplayer -dumpstream rtsp://whatever/stream.rm
-
record rtsp streams to disk with mencoder (use mplayer-plugin’s "Copy URL" feature to capture the url)
$> mencoder rtsp://whatever/stream.wmv -ovc copy -oac copy -o output.wmv
-
encode rtsp steams to disk with mencoder (use mplayer-plugin’s "Copy URL" feature to capture the url)
$> mencoder rtsp://whatever/stream.wmv -ovc lavc -oac mp3lame -o output.avi
-
convert wma files to ogg (requires win32 codecs)
$> for i in *.wma; do mplayer -ao pcm -aofile "${i%.wma}.wav" "$i"; oggenc "${i%.wma}.wav"; rm "${i%.wma}.wav"; done
-
record from line-in (or microphone) to mp3 (you will need to adjust your capture volume level)
$> arecord -f cd -t raw | lame -r - out.mp3
-
disable screensaver (can be put in a loop shorter than screensaver interval to keep it dead); mplayer also has a disable option
$> gnome-screensaver-command -deactivate
-
Convert recordmydesktop ogv file to flv
$> ffmpeg -i input_file.ogv -b 1600k -ar 11025 output_file.flv
-
Naming of Sound devices (e.g., hw:0,0)
Desktop
$> Set which program opens when media (CD, DVD, Digital Camera, etc) is inserted in Gnome
-
Open up Nautilus, select Edit > Preferences from the menu and set the program to handle each event in the Media tab
Package Management
-
find which package owns a file
$> rpm -qf /path/to/file
-
query rpm packages by short name
$> rpm -qa --qf "%{NAME}\n"
-
list installed rpm names sorted by size
$> rpm -qa --queryformat '%10{SIZE} %{NAME}\n' | sort -n -r
-
reinstall an rpm
$> rpm -Uvh --replacepkgs rpm_packagename.rpm
-
build an rpm from a tarball
$> rpmbuild -tb application.tar.gz
-
show all tags available for rpm queryformat
$> rpm --querytags
-
show all rpms (name, version-release, installed date)
$> rpm -qa --qf "%{NAME}\t%{VERSION}-%{RELEASE}\t%{INSTALLTIME:date}\n" | sort
-
show all rpms (name, installed date) by recently installed
$> rpm -qa --last
-
Import a GPG key into the RPM repository (ascii public key)
#> rpm --import http://www.jpackage.org/jpackage.asc
-
Extract files from an rpm archive (into current directory)
$> rpm2cpio package.rpm | cpio -idmv --no-absolute-filenames
-
Hold back packages (space separated) from being updated by yum in /etc/yum.conf
$> exclude=packagename1 packagename2
-
Build a debian package when compiling from source (also see http://www.linux.com/articles/60383)
$> ./configure make checkinstall
-
Hold back a debian package from being upgraded
$> echo "firefox hold" | dpkg --set-selections
Text Manipulation
-
append "content" as root to file "target-file" using sudo
$> echo "content" | sudo tee -a target-file > /dev/null
-
convert DOS text file format to UNIX, specifically endlines (part of sysutils debian package)
$> fromdos FILE
-
remove unprintable characters, except for spaces
$> cat file-in.txt | tr -d -c [:print:][:space:] > file-out.txt
-
find and replace text in a set of files
$> find -type f -exec sed -i 's/search/replace/' {} \;
-
occationally the terminal will get out of whack; one simple command can make it work as expected again
$> reset
-
apply a patch, removing files that are marked as deleted in the patch, with a fuzz factor of 2
$> patch --dry-run -F 2 -E -p0 < patch.txt
-
open file in vim so you can see the BOM
$> vim -b file-with-bom
-
find non-ascii characters in a file
$> grep -P -H -n "[^[:graph:][:space:]]" FILE
Bash & Shell
-
test bash script for syntax without executing
$> bash -n script.sh
-
glob matching all the files in a directory, including hidden files (files that begin with .)
$> * .[^.]*
-
run command, bypassing any alias
$> \command
VIM
-
jump to a byte offset in the buffer (a file)
$> :go 456
Git
-
Remove file(s) from git history
$> git filter-branch --index-filter 'git rm --cached --ignore-unmatch <file>' HEAD $> rm -rf .git/refs/original/ && git reflog expire --all && git gc --aggressive --prune
CVS
-
Check files which have changed after a specified date
$> cvs log -NS -R -d ">YYYYMMDD"
-
Run synchronization report
$> cvs -nq update -Pd 2>&1 | grep -v "cvs update: New directory"
-
Synchronize with repository
$> cvs -q update -Pd 2>&1 | grep -v "cvs update: New directory"
SVN
-
Merge a feature branch into the trunk (with dry run option)
$> cd trunk $> svn merge --dry-run -r BASE:HEAD http://svnhost/path/to/branch
-
Specifying username for svn+ssh other than login name
$> export SVN_SSH='ssh -l username'; svn commit filename
-
When doing an import, you have include the directory name that you want to create
$> svn import new-project http://svn.host/svn.path/new-project
Maven 2
-
Create an empty web application project
$> mvn archetype:create -DgroupId=com.mycompany.myapp -DartifactId=myapp -DarchetypeArtifactId=maven-archetype-webapp
-
Synchronizing select directories from a maven mirror
$> rsync -azv --include /sf --include /sf/saxon --exclude "/*" --exclude "/*/*/" rsync://ftp.ibiblio.org/pub/packages/maven2/net/ ./
MySQL
-
Change root user password
$> /usr/bin/mysqladmin -u root -p password 'new-password'
-
Give user access to all tables
mysql> GRANT ALL PRIVILEGES ON *.* TO some_user@localhost IDENTIFIED BY 'some_pass' WITH GRANT OPTION; mysql> FLUSH PRIVILEGES;
-
Change password for existing user
mysql> SET PASSWORD FOR 'user'@'hostname' = PASSWORD('passwordhere'); mysql> FLUSH PRIVILEGES;
-
Reset auto-increment value for table
mysql> ALTER TABLE tbl_name AUTO_INCREMENT = 1;
-
Backup a single database
$> /usr/bin/mysqldump --complete-insert --add-drop-table --lock-tables --user=username -p database > backupfile.sql
-
Cancel a partially typed query
mysql> select * from \c
-
Display results as records rather than in tabular form
mysql> select * from table \G
Services & Run Levels
-
Add a system startup service in Debian (where servicename is the name of the startup script)
#> /usr/sbin/update-rc.d servicename defaults
-
Remove a system startup service in Debian (where servicename is the name of the startup script)
#> /usr/sbin/update-rc.d -f servicename remove
-
Shutdown (halt) a system
#> halt
-
Reboot a system
#> shutdown -r
-
Go to another runlevel (in this case 3)
#> telinit 3
Network
-
Setting the system hostname (be sure to add it to /etc/hosts as well)
#> echo server1.example.com > /etc/hostname; /bin/hostname -F /etc/hostname
-
notify KDE of change in hostname
$> kdontchangethehostname old_hostname new_hostname
-
check if a host is available (for a given port)
$> nc -z hostname 22 -w 1 >/dev/null 2>&1 && echo connected!
-
Find computers on local network with an open SSH port
$> nmap -p 22 --open -sV 192.168.0.1/24
-
Access a local computer when connected to the VPN
$> ssh hostname.local
-
After updating the /etc/aliases file, it is necessary to update the database using
#> newaliases
Job Control
-
Where’s my crontab?
$> /var/spool/cron/$USERNAME
-
Start a job in the background, disconnected from terminal (
joblist
is a file with a list of commands)
$> at -f joblist now
-
Execute an X windows application in cron (add to top of crontab file)
DISPLAY=:0
-
Kill processes matching a pattern (where
$PATTERN
is the search string)
$> ps -e -opid,command | grep $PATTERN | awk '{print $1}'| xargs kill -9
-
Prevent command from exiting even if you disconnect from the shell
$> nohup command
-
Watch the output of a command as its results change in real time
$> watch df
Kernel Modules
-
Disable USB 2.0 (to prevent autoloading, add it to /etc/hotplug/blacklist)
#> rmmod ehci_hcd
-
After removing a loadable module, be sure to run
/sbin/depmod
to update the dependencies and module load sets
Apache Configuration
-
In order to strip the query string when using mod_rewrite, append a
?
to the end of the redirect and the query string will be dropped
RewriteRule ^oldpath/index.php$ /newpath/index.php? [R=301,L]
SSH
-
Pass an option to SSH (in this case don’t allow a regular password prompt)
$> ssh -oNumberOfPasswordPrompts=0 user@hostname
-
Copy public rsa key directly into authorized_keys2 file on remote host
$> cat ~/.ssh/id_rsa.pub | ssh $USER@$REMOTE_HOST "cat >>~/.ssh/authorized_keys2"
-
Another way to copy public rsa key around:
$> ssh-copy-id -i ~/.ssh/id_rsa.pub $USER@$REMOTE_HOST
-
Establish an ssh tunnel using a local port to route traffic to a remove service
$> ssh -L $LOCAL_PORT:localhost:$REMOTE_SERVICE_PORT -f -N $USER@$REMOTE_HOST $> # an example with real values to tunnel SMTP traffic through SSH using an alternate port $> ssh -L 8025:localhost:25 -f -N user@example.com
-
Setup a proxy tunnel, so that you can access the internet through another computer
$> ssh -f -N -2 -C -D 4567 $USER@$REMOTE_HOST
-
Setting up a reverse ssh tunnel
$> ssh -R $TUNNEL_PORT:localhost:22 -f -N $USER@$REMOTE_HOST
-
Connecting to reverse ssh tunnel
$> ssh -p $TUNNEL_PORT localhost
-
Tunnel HTTP traffic through reverse ssh tunnel
$> ssh -L $LOCAL_LISTEN_PORT:localhost:80 -f -N -p $TUNNEL_PORT $USER@localhost
Note: If you are going to use tunneling from different hosts, it might be convenient to set the ssh_config variable NoHostAuthenticationForLocalhost
to yes to prevent those nasty messages
X Windows / Graphics
-
Copy to clipboard
$> echo hi | xclip
-
Take a screenshot, with optional delay
$> sleep 3s; import -window root screenshot.png
-
Get window information (particularly id)
$> xwininfo
-
Rearrange desktop icons in KDE
$> dcop kdesktop KDesktopIface rearrangeIcons
-
Enable the nvidia driver
$> sudo nvidia-glx-config enable
-
Restart X within a session
CTRL+ALT+Backspace
-
Restart X from login screen (xdm/gdm/kdm)
ALT+e
Homebrew
-
Install a specific version of a package
* Install a specific version of a package
wget https://raw.githubusercontent.com/Homebrew/homebrew-core/<hash>/Formula/n/name-of-package.rb brew install --HEAD ./name-of-package.rb
== elsewhere... * http://emacswiki.org/emacs/MovingTheCtrlKey[Moving the Ctrl Key] * http://dokuwiki.splitbrain.org/snippets[Splitbrain's Code Snippets] * http://www.pixelbeat.org/cmdline.html[Pixelbeat's Linux Command Line Tips] * http://fosswire.com/2007/08/02/unixlinux-command-cheat-sheet[Unix/Linux Command Cheat Sheet] * http://www.scottklarr.com/topic/115/linux-unix-cheat-sheets---the-ultimate-collection[Linux/Unix Cheat Sheets - The Ultimate Collection] * http://www.laclinux.com/en/LAC_HOWTO[Los Alamos Computers HOWTO collection] * http://matt.might.net/articles/ssh-hacks/[Matt's SSH Hacks] * http://www.techbar.me/linux-shell-tips/[Linux Shell Tips] * http://www.tecmint.com/11-lesser-known-useful-linux-commands/[Lesser Known Linux Commands] (multi-part series) * https://blog.testdouble.com/posts/2020-04-07-favorite-things/[A few of my favorite things]