linux-commands-cheat-sheet
linux-commands-cheat-sheet
test[‘condition’][‘condition’]
Evaluate arguments as an expression:
expr
expr `arguments`
To view contents of a simple file on stdout
-n To print line numbers as well
cat
-s To suppress repeated blank lines
-b To number only non-empty lines (overrides -n)
tac To view contents of file in reverse (last line 1st)
To view contents of large files one screen at a time. It also displays % of
file displayed and we can’t move back up in it.
ENTER To move down line-by-line
more SPACE To move down one screen
/str To search “str” in file.
Press 'n' to find next
Press 'N' to find previous
To view contents of large files one page at a time but much better than
Navigation Arrow keys, Pgup, Pgdwn, ENTER, SPACE (acts as Pgdwn), HOME, END
/str To search “str” in file.
less Press 'n' to find next
Press 'N' to find previous
g, G 'g' moves to start and 'G' moves to end
“more”.
Displays 1st ten lines
head
-n To view 1st n lines
Displays last ten lines
-n To view last n lines
tail
-f Output appended data as the file grows
-c specifies that we want to read n characters not lines
User defined names for commands (arguments are also allowed in alias)
alias alias cls="clear" #makes “cls” an alias for clear command
alias #list all aliases
To remove alias
unalias
-a Remove all alias definitions
To display calender
-h Won’t highlight current-date.
-m Display the specified month
cal
yyyy Display a calendar for the specified year (e.g. cal 2017)
-1 Displays only the current month.
-3 Display the previous, current and next month.
date To display and change (only for root) date [day MON dd mm:hh:ss PKT yyyy]
To shut-down or restart
shutdown now Shut-down immediately
shutdown -r Restarts immediately
shutdown now
shutdown +0 Shut-down immediately
shutdown +m Shutdown after m minutes (‘+’ is optional)
shutdown 22:30 Shut-down at 22:30
To copy files/directories
-p Preserve permissions while copying (by default permissions can change)
cp
-r For directories
e.g: cp f1 f2 #f1 is source file and f2 is target-file
To remove files/directories
-f ignore non-existent files and arguments, never prompt
rm -r For directories
-i For confirmation prompt
e.g: rm f1 f2 #will delete both f1 & f2
To move files/directories
mv -i For confirmation prompt
e.g: mv f1 f2 #will move f1 to f2 (it is also used to rename file)
To make directory file
mkdir -m set file mode (as in chmod)
-p no error if existing, make parent directories as needed
To remove directory file
rmdir -p remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is similar
to 'rmdir a/b/c a/b a'
Gets input from stdin and output it on stdout after sorting
-b Ignore leading blanks
-r for reverse order
-t for specifying delimiters (e.g.: -t";")
-kn to sort by column n
sort -n for numeric sort
-c check for sorted input; do not sort
-d Dictionary order
-f fold lower case to upper case characters
-i consider only printable characters
-g compare according to general numerical value (general numeric sort)
length a string operation to return the number of characters stored in a string
Resource Person: Muhammad Arif Butt (PUCIT)
Vim Editor
Command Description
sudo apt-get To install vim editor
install vim
vimtutor For detailed vim lessons
vim + For opening file in append mode (cursor at last line)
vim +n Cursor at start of line-n
vim +/string Cursor on line with 1st occurence of "string"
ESC Command mode
ESC+: Last-line mode
q To quit vim
i Start typing before current character
I Start typing from beginning of current line
a Start typing after current character
A Start typing from end of current line
o Open new line below current line
O Open new line above current line
h To move cursor left
L To move cursor right
K To move cursor up
j To move cursor down
gg To goto 1st line
GG To goto last line
End, $ Moves to end of current line
Home, 0 Moves to start of current line
Shift+G To put prompt at the end of document
u For undo
Ctrl+r For redo
Then write string to search.
/ For forward search
ESC+[/,?] ? For backward search
n Find next
N For finding in opposite direction
dw For deleting a word
[n]dd For deleting a line
[n]yy For copying line
[n]p For pasting n times below current line
[n]P For pasting n times above current line
Resource Person: Muhammad Arif Butt (PUCIT)
File Management
Command Description
lsattr View extended file attributes
Change extended file attributes
chattr
chattr +/-[attr] file
For creating links.
ln
-s For soft-links
tty Display the name of terminal you are using
xterm to launch ptmx terminal
To change and print terminal line settings.
stty attribute value
-a To view all attributes
stty sane To reset all attributes to their defaults.
stty
-isig To off signals on terminal
-g To save terminal settings
stty -echo Turns off terminal echo
stty echo Turns on terminal echo
File Permissions Management
Change user owner
chown chown :group file (for changing grp owner using chown)
chgrp Change group owner
For changing permissions
chmod
If we write "chmod +r" r will be assigned to u/g/o
To view/change umask
umask -S To view complement of umask in symbolic way
Foreach file, getfacl displays the file name, owner, the group, and
getfacl the Access Control List (ACL). If a directory has a default ACL, getfacl
also displays the default ACL.
Sets file ACL
-m add entry
-x remove entry
setfacl
-b clear acl and delete all entries
-d add default entry
-R add recursive entry
Process Management
Command Description
Lists currently running jobs and their status
jobs -l lists process IDs in addition to the normal information
-p lists process IDs only
User Management
Resource Person: Muhammad Arif Butt (PUCIT)
Command Description
visudo used to edit /etc/sudoers file
adduser More interactive and recommended (sudo adduser user1)
It is low-level command to add user.
And we need to give some extra info as well. Its minimum requirements are:
useradd -m to make directory of that user
-d To specify directory path (/home/username)
useradd -m -d /home/user2 user2
User we want to delete should be logged out. It don't deletes user HOME
deluser
Dir
Low level also deletes HOME directory and files.
userdel -r to delete home dir and associated files as well of this user.
sudo userdel -r user1
To modify user info.
e.g.: usermod -a -G gp2 user1 (makes user1 member of gp2)
• If we don't use -a then it will not append new user but overwrite it
(that is all previous group members will be removed)
-c to change personal info column value
sudo usermod -c "Personel Info" user2
-s to change default user shell
sudo usermod -s /bin/sh user2
usermod -l to change username
sudo usermod -l user007 user2 (new name 1st)
-d to change Home Directory
-L to lock user (this user can't log in)
-U to unlock locked user
-g to change primary group
-G to change secondary group
-a, -- Add the user to the supplementary group(s). Use only with
append the -G
groupadd To add new group. (sudo groupadd gp1)
groupmod To modify group. -n is used for changing group name.
groupdel To delete group. (sudo groupdel name)
Used to change password expiry info of a user (sudo chage user2).
chage -l to view just password setting of particular user
chsh Used to change default user shell
chfn Used to change user personal info
finger shows user info in detail (may have to install it manually)
it displays ID (UID) and primary GIDs and groups you belong to
id
gid=primary group, groups = Secondary group
(switch user) We can use it to login using any username if we know its
password (e.g: su -root)
su • Using '-' will also give you the target user environment. You will
find yourself in the target user HOME Directory and his default login
shell
Disk/Memory Management
Command Description
Disk Formatting
man fs Man page for all commonly used file-systems and their characteristics.
to build filesystem (format partitions)
• its use is deprecated now there are commands for each FS like mkfs.ext, mkfs.ext2 etc.
mkfs
mkfs.<FS_Name>
• There should not be any data on partition we want to format if there is take its backup
To mount a partition.
mount mount -t type device /dir
mount /dev/sda3 /opt (mounts /dev/sda3 to /opt)
unmount To unmount a partition. (umount /dev/sda3)
Lists info about all available block devices (sda, sr0)
• It shows 7-columns by default
• To view only selected columns, use -o then enter names of columns (,
lsblk
seperated)
lsblk /dev/sda (List info about /dev/sda only.)
lsblk -o name,type,fstype,parttype,size,mode /dev/sda
FS Architecture
Changes label on ext2/ext3/ext4 file systems.
e2label e2label /dev/sda3 "anas3" To assign label
e2label /dev/sda3 "" To unassign label
Shows super block info in detail:
tune2fs
tune2fs -l /dev/sda1
Lists all i-node block info of a file or device e.g.: inode, permissions,
stat times, size, owners etc.
stat filename/device
stat /etc/passwd
stat -f /dev/sda1 (-f shows info about device e.g: /dev/sda1)
(Disk free) Displays amount of diskspace available on partition/FS
df -i devices
df
If no devices are mentioned then list info for all active partitions.
-i shows info about inodes
(Disk usage) Displays how much space a particular file or directory has
occupied.
du
-h shows size in human readable form K, M, G
du ~ Recursively shows sizes of all files, dir, sub-dirs inside ~
(List of opened files) System Wide File Table
lsof
lsof -p PID (list files opened by PID only)
• Identify process using files or sockets.
• Used to list PIDs and usernames of processes using a specific file
fuser
-u To show username as well
fuser -u /etc/passwd
Disk Partitioning
Tell the kernel about the presence and numbering of on-disk partitions
partx partx --show /dev/sda (List all partitions on Disk)
Copy a file, converting and formatting according to the operands.
dd if=/dev/sda bs=512 count=1 (Shows contents of zero sector but not
human readable)
dd • It will read file /dev/sda and (if=/dev/sda)
• reads just 512 bytes and (bs=512)
• read once and show them (count=1)
• The hexdump utility is a filter which displays the specified files, or
the standard input, if no files are specified, in a user specified
format.
• Makes content of dd readable.
hexdump -C Display the input offset in hexadecimal, followed by sixteen
space-separated, two column, hexadecimal bytes, followed by the
same sixteen bytes in %_p format enclosed in ``|'' characters.
dd if=/dev/sda bs=512 count=1 | hexdump -C
(Shows zero sector in readable HEX format)
Manipulate disk partition table (interactive program)
-l shows info about all the block devices and their partitions
• fdisk -l /dev/sda (shows info about sda only)
• fdisk –version (to check fdisk version)
• To run fdisk use “fdisk /dev/sda” as root/sudo
m For help.
p Displays partition table
d To delete partition
fdisk n To create new partition
p=primary,e=extended
then write partiton digit (1-4)
1st sector (use default)
last sector or size (we should use size in human form by
proceding with +) e.g: +2G
(default for last partition is all remaining disk space)
q quit without saving changes
w write table to disk and make changes permanent (use it
carefully)
ar -x /usr/lib/libm.a
-t display table of contents of an archive
ar -t /usr/lib/libm.a
-c Without it if an archive is not already existing then a
warning will be displayed.
-s To maintain files in particular order w.r.t to functions to
avoid errors
ranlib utility generates an index to the contents of an archive and stores it
ranlib in the archive.
List dynamic dependencies displays the shared libraries that an executable (or
ldd
a shared library) requires to run.
Conf igure dynamic linker run time bindings. Creates necessary links to the
ldconfig
most recent shared library verions
This command can be used to obtain various information, including disassembled
objdump binary machine code from an executable file, compiled object or shared library.
-d To disassemble
This command lists the set of symbols def ined within an object library or
nm
executable program
objcopy Copy and translate object files.
addr2line Convert addresses into file names and line numbers
GNU Compiler: gcc [options] file-list
-o Specify the name of executable file (default a.out)
-save-temps To save all intermediate files: (*.i, *.s, *.o, a.out)
-E Perform preprocessing only and generate file with .i
extension
-S Generate Assembly code with .s extension for the specific
processor
-c Suppress linking phase and keep object files with .o
extension
gcc -static To force static linking
-lxxx All libraries except std I/O, need to be explicitly linked
with -l option.
-Lpath By default, linker looks for libraries in /usr/lib/x86_64/
and /lib/ directories. If you want to link libraries
located somewhere else, use -L option
-Ipath By default, preprocessor first searches for include files
in directory containing the source file, then in the
directory named with -I option to gcc, and finally in
/usr/include/ or /usr/include/c++/4.1.1
GNU Compiler
we can also specify exe file with it to load it at startup, then we won’t have
gdb to use file command
-tui to open gdb in ncurses-interface mode (default 2 panels
{code,command})
To generate core file in case of abnormal termination.
ulimit -c unlimited
gdb -q ex2 core
• Project: ProjectDir/.git/config
• ./.git/HEAD (tell branch)
• ./.git/refs/heads/master (master=branch)
HEAD
• .git/refs/remotes/origin/master (remote master
HEAD)
• Project Level: .git/info/exclude
Excluding files
• Directory Level: ./.gitignore