Unix Command Line Notes
Command settings
.bashrc
alias [alias-name]='[alias command(s)]alias ls='ls -lh'.profile or .bash_profile
source .profile to reload the profile![number] will repeat one of the commands storied in the historyhistory | grep [search] will display only the commands in the history that match your search queryman [command] to get documentation for a particular command
q will exit out of manual pagesManipulating files
pwd - print working directorydf - report on disk usagels /[directory-path] - list files within a directory
-a show hidden files and directories (all files)-d gets directory information (in addition to the files in that directory)-l long listing-R list files recursively-F classify files with special characters: display a / after each directory, @ after each link, and * after each executable (normal files have nothing special)-s include the number of blocks the file takes up (for more accurate space indication of what the file actually uses on the disk)-h for human readable file sizes-e show ACLs, if present-t shows files from most recently edited−1 lists files in a single columncp [filename/folder] [destination] - copies files
-i asks for confirmation before overwriting existing files-a preserve symbolic links (-d), recusively (-R), and reserve attributes (preserve=all)rm [file/folder] - remove a file or directory
-f force removal-r remove recursively (everything inside)-i ask for confirmation-d removes directories-v for verbose outputmv [file] [new-file-name] or mv [file] [/new-destination] - renames or moves files or foldersdu - space a file/directory takes uptouch [filename]
cat [filename] - displays the contents of a file"[contents]" > [filename] will create a new file or replace the existing file with the contents you specify"[contents]" >> [filename] will append the contents to an existing file (or create a new file with those content)ln -s [/path/destination] [sym-link name]rsync [options] [source] [destination]
Copies only the folders/files that have been changed from one location to another
Can be used over network connections (local <-> remote)
End the path with / to indicate copy just the contents of a folder, and not the folder itself
Remote destinations can be indicated through ssh user@server:/path/to/files
rsync to backup a Mac system volume
sudo rsync -avPE --exclude "/Volumes" --exclude "/dev" --exclude ".MobileBackups.trash" / /destination
Options
-a archive mode: recursive, preserves symbolic links, preserves permissions, preserves timestamps, preserves owner and groups (generally a good idea to use this)-E copy extended attributes, including resource forks and ACLs (mac only)-e ssh indicates use a remote shell and use ssh for transfer-h human readable output-i view the differences (without modifying files) between destination and source
f indicates a files size changet timestamp changeo owner changeg group change-n or --dry-run to run through changes without modifying any files-r recursive through folders-u don't overwrite modified files in the destination-v verbose, output each file-W transfer the whole file that's been changed, instead of just the block(s) that have been changed-z use compression (most useful for local to/from remote syncs)--backup--backup-dir--suffix--delete deletes files in the destination that are not in the source directory--existing copy/update only the existing files in source to the destination--include "[pattern]" or --exclude "[pattern]" to include/exclude certain files
--exclude-list will specify a text file with a list of exclude patterns, one on each line--max-size="[size]" to set the max size of files to be transfered--progress or -P to see the overall progress of the operationProcesses
ps show currently running processes
-a show processes from all users (with open terminals)-f display extra information, like uid, pid, CPU usage, etc-l long listing-m sort by memory usage, rather than name/id-r sort by current CPU usage-u display processes belonging to the specified user names-x display all processes, even if they don't have a controlling terminal| grep [process-name] to show only the processes you are looking fortop displays a dynamic updated list of running processes (default sorted by pid)
-o [key] changes the order of the process list; keys include
cpu cpu usageuid user iduser user namekill [process-id] will stop a process by its id
−9 will force kill it by sending KILL-s to send a specific signal other than TERMkillall [process-name] kills all instances of a process by namePackages
lsbom lists the files installed by a package
-f lists files-l lists symbolic links-s prints only the path of each file-h prints the full usage of each filetar [options] [source] [destination]
tar is just a collection of files within a single tar filetar.gz or .tgz is a compressed tar
-z optiontar then compress with gziptar -cjvf [file] [destination] creates a compressed tarfiletar -tvf [file] lists contents without extracting the filetar -xvf [file] extracts a file in the current directory-c create-r replace-x extract/restore-w ask confirmation for each file-v verbose-j compress using bzip-z compress using gzipmpkg
xar -xvf [package] extracts a package filexar -c [source] -vf [destination] compresses a package-c create/compress-x extract-v verbose-f filesunzip [options] [zip-file-to-unzip] [list-of-specific-files-to-unzip] [-x files to exclude] [-d where to unzip files]
-f freshens existing files, extracting only files that already exist on disk and are neweropen [filename.zip] will unzip zip files as wellDirectories
cdcd will take you to the previous working directorycd ~pushdpopdPermissions and ACLs
d rwx rwx rwx
d directory, - file, l link, s socket filer read (4)w write (2)x execute (1)u)g)o)chmod [options] [permission] [filename] (to set permissions) or chmod [filename] (to see permissions)
g+w adds write permissions to groupchown [user]:[group] [files]
: you specify-R recursive for all files and folders within a directory-H will effect symbolic links if -R is set (not effected by default)-h change the mode of the symbolic links, but not follow them-L follow symbolic links (change all files and folders within links)-P symbolic links are uneffected (this is the default)-f do not display an error message-v verbosefind . -type f -print0 | xargs -0 chmod 644find . -type d -print0 | xargs -0 chmod 755Clipboard
pbcopy - copies contents of file into your clipboard
pbcopy < path/file.txtpbpaste - allows use of the clipboard in terminal
pbpaste > path/file.txt - writes the contents of the clipboard into a fileSearching files
grep -[flags] [search-pattern] [target-directory/file] (global regular expression print)
-R - search recursivelyegrepfind [path] -[option] [query]
-mtime searches by modification time
find . -mtime 1 searches for all files modified exactly 1 day agofind . -mtime -1 searches for all files modified within the last dayfind . -mtime +1 searches for all files modified more than a day ago-atime searches by last accessed time-ctime searches by last changed time-cmin searches by last changed time in minutes-perm searches by permission
find . -perm 644 finds all files with 644 permissions-name
-iname is case insensitive-delete will delete the files found using the find command-type
find [path to install] -type d -exec chmod 755 {} \; will find all directories and change their permissions to 755find [path to install] -type f -exec chmod 644 {} \; will find all files and change their permissions to 644xargs
find . -name "*.tmp" | xargs rm -f to remove .tmp filesfind . -name "*.txt" | xargs grep "text" will find all text files that contain a certain textSearch and replace
sed 's/[regex-to-replace]/replacement/ oldfile > newfile' - search and replace
/ is the default delimiter; any character can be used, and it's best to use a character that's not in the search or replace string (: and | are popular)& can be used in the replacement string; it represents what is found in the search stringg after the replacement delimiter to replace every occurrence of the matched expression (only replaces the first occurance on each line, by default)-i 'filename' to output directlyi to a file - use -i '' on osx if you want to overwrite the original fileperl
perl -i -pe 's/search/replace/g' [filename]
-i read from file; use -i.bak or similar to create a backup-e define perl code to be executed (in '')-p adds loops around -e codes/search/replace/)
g - replace all occurrences of the pattern (not just the first)m - search across line breakss - include line breaks as any other letteri - case insensitive searchperl -i -pe 'undef $/; s/search/replace/smg' [filename]File comparison
diff [file1] [file2] to compare files line by line
-u unified output (use this unless you have a reason not to)-i ignore case-E ignore changes due to tab extension-b ignore whitespace changes-w ignore all white space-B ignore all lines that are blankdiff -u [original-file] [new-file] > file.patchpatch -R < file.patch
-R will reverse the patch-b makes backupsNano text editor - nano [filename]
-w start nano with line wrapping off (important for configuration files)Alt+MCtrl + w search within a fileAlt + w find nextCtrl + k cut lineCtrl + u paste lineCtrl + k then paste all with Ctrl + uNetworking
hostname - find host/domain name and IP address
-d displays the domain name the machine belongs to-f displays the fully qualified host and domain name-i displays the IP address for the current machineping [hostname] - test network connection by sending packets of information to the defined source (also used for testing speed of connection)
do to begin continuous test; use Ctrl + C to stop the testifconfig - get current network adapter configurationnetstat - network connections, including routing tables, interface statistics
-g find all the multicast groups (network) subscribed to this hostnetstat -nap | grep [port-number] - display process id of application which is using the specified port-a or -all will display all connections including TCP and UDP-r for routing tables--tcp or -t will display only TCP connections--udp or -us will display only UCP connectionsnslookup [hostname or ip address] - query DNS lookup name
telnet [hostname] [port] - check status of destination hosttraceroute - view number of hops and response time to get to a remote system or web sitefinger - view user information (user name, real name, terminal name, and write status); old command, rarely usedroute -v add -net 10.208 -interface ppp0
10.208 through the VPN connection (PPP0)curl - get remote files
-O [url] downloads a file and writes it with the same name-o [filename] [url] downloads a file and lets you specify the namelsof -i scan active ports for local machineiptables
Checksums
md5 [filename]shasum [filename] (for SHA1)
-a to change to 224, 256, 384, or 512Efficiency tips
![command] to quickly redo the previous command (including flags and arguments)!! for executing the previous command exactly as typedCtrl + R + [search] will search for the last command that contains whatever words you typehistory | grep "[keyword]" searches the UNIX command history| (pipe symbol) to separate multiple commands on the same line.bashrc or .profileCtrl + Z to suspend a processfg [number] or bg [number] to bring suspended processes to the foreground or backgroundUsers
adduser [username] creates new users and prompts you for the detailsuseradd creates new users and lets you manually specify each option
-d /home/username specifies the location of the home directory-m forces the creation of the home directory-g/--gid [group] lets you specify which group to add the user to (check adduser.conf to see what the default is)-G/--groups [group1,group2,etc] for supplementary groups--disabled-password prevents password logins (as for when only using SSH keys)passwd [user] sets the password for a user
-l changes the user's password to an untypable string so it can't be used to login/etc/adduser.conf
755su [username] will switch to a particular user (useful to become the root user)cat /etc/passwdusermod [options] [username] modifies user information
-g [group] change the user's initial login group-a -G [group1,group2,etc] [user] will add a user to supplementary groups (the -a adds the user to those additional groups; without it, the user will be removed from any groups not specified-c "Desired Name" [user] to change a users full namedeluser [user] [group] will delete that user from the groupgroups [user] will display a list of groups for that usergroupadd and groupdel to add and remove groupssudo visudo to configure which users can use sudo/etc/passwd lists each user and determines which shell they run when logged in