-
Command settings
.bashrc- Aliases - place the following on a new line in the .bashrc file
alias [alias-name]='[alias command(s)]- Ex:
alias ls='ls -lh'
- Aliases - place the following on a new line in the .bashrc file
.profileor.bash_profile- Add folders to you path
- Use
source .profileto reload the profile
- history
- By default, remembers the previous 100 commands you've typed
- history will list the stored comands
![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 query
man [command]to get documentation for a particular commandqwill exit out of manual pages
-
Manipulating files
pwd- print working directorydf- report on disk usagels /[directory-path]- list files within a directory- Specifying a directory is optional; will list the current directory by default
-ashow hidden files and directories (all files)-dgets directory information (in addition to the files in that directory)-llong listing-Rlist files recursively-Fclassify files with special characters: display a / after each directory, @ after each link, and * after each executable (normal files have nothing special)-sinclude the number of blocks the file takes up (for more accurate space indication of what the file actually uses on the disk)-hfor human readable file sizes-eshow ACLs, if present-tshows files from most recently edited−1lists files in a single column- -r reverse the sort order
cp [filename/folder] [destination]- copies files- Automatically overwrites destination
-iasks for confirmation before overwriting existing files-apreserve symbolic links (-d), recusively (-R), and reserve attributes (preserve=all)
rm [file/folder]- remove a file or directory- Normally, a directory must be empty to remove it
-fforce removal-rremove recursively (everything inside)-iask for confirmation-dremoves directories-vfor verbose output
mv [file] [new-file-name]ormv [file] [/new-destination]- renames or moves files or foldersdu- space a file/directory takes uptouch [filename]- For existing files, updates the accessed time
- If the file doesn't exist, it creates a new, blank file
cat [filename]- displays the contents of a file- Replace or add to files
"[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)
- Symlinks (for soft links, which can span partitions)
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
-
rsyncto backup a Mac system volumesudo rsync -avPE --exclude "/Volumes" --exclude "/dev" --exclude ".MobileBackups.trash" / /destination -
Options
-aarchive mode: recursive, preserves symbolic links, preserves permissions, preserves timestamps, preserves owner and groups (generally a good idea to use this)-Ecopy extended attributes, including resource forks and ACLs (mac only)-e sshindicates use a remote shell and use ssh for transfer-hhuman readable output-iview the differences (without modifying files) between destination and sourcefindicates a filessize changettimestamp changeoowner changeggroup change
-nor--dry-runto run through changes without modifying any files-rrecursive through folders-udon't overwrite modified files in the destination-vverbose, output each file-Wtransfer the whole file that's been changed, instead of just the block(s) that have been changed-zuse compression (most useful for local to/from remote syncs)- Backups
--backup--backup-dir--suffix
--deletedeletes files in the destination that are not in the source directory--existingcopy/update only the existing files in source to the destination--include "[pattern]"or--exclude "[pattern]"to include/exclude certain files- Can be used multiple times to specify multiple files
--exclude-listwill 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--progressor-Pto see the overall progress of the operation
-
-
Processes
psshow currently running processes-ashow processes from all users (with open terminals)-fdisplay extra information, like uid, pid, CPU usage, etc-llong listing-msort by memory usage, rather than name/id-rsort by current CPU usage-udisplay processes belonging to the specified user names-xdisplay all processes, even if they don't have a controlling terminal- Use with
| grep [process-name]to show only the processes you are looking for
topdisplays a dynamic updated list of running processes (default sorted by pid)-o [key]changes the order of the process list; keys includecpucpu usageuiduser iduseruser name
kill [process-id]will stop a process by its id−9will force kill it by sending KILL-sto send a specific signal other than TERM
killall [process-name]kills all instances of a process by name
-
Packages
lsbomlists the files installed by a package-flists files-llists symbolic links-sprints only the path of each file-hprints the full usage of each file
tar [options] [source] [destination]- Types
taris just a collection of files within a single tar filetar.gzor.tgzis a compressed tar- Use
-zoption - Use
tarthen compress withgzip
- Use
tar -cjvf [file] [destination]creates a compressed tarfiletar -tvf [file]lists contents without extracting the filetar -xvf [file]extracts a file in the current directory- Options
-ccreate-rreplace-xextract/restore-wask confirmation for each file-vverbose-jcompress using bzip-zcompress using gzip
- Types
mpkgxar -xvf [package]extracts a package filexar -c [source] -vf [destination]compresses a package- Options
-ccreate/compress-xextract-vverbose-ffiles
unzip [options] [zip-file-to-unzip] [list-of-specific-files-to-unzip] [-x files to exclude] [-d where to unzip files]-ffreshens existing files, extracting only files that already exist on disk and are newer
open [filename.zip]will unzip zip files as well
-
Directories
cdcdwill take you to the previous working directorycd ~pushdpopd
-
Permissions and ACLs
- Permissions
d rwx rwx rwxddirectory, - file,llink,ssocket filerread (4)wwrite (2)xexecute (1)- user (
u) - group (
g) - others/world (
o)
- Number of hardlinks
- Owner and group
chmod [options] [permission] [filename](to set permissions) orchmod [filename](to see permissions)- Example:
g+w adds write permissions to group
- Example:
chown [user]:[group] [files]- Can enter user, group, or both, depending on which side of the
:you specify - Options
-Rrecursive for all files and folders within a directory-Hwill effect symbolic links if-Ris set (not effected by default)-hchange the mode of the symbolic links, but not follow them-Lfollow symbolic links (change all files and folders within links)-Psymbolic links are uneffected (this is the default)-fdo not display an error message-vverbose
- Can enter user, group, or both, depending on which side of the
- Change permissions of files or folders
- Files only
find . -type f -print0 | xargs -0 chmod 644 - Folders only
find . -type d -print0 | xargs -0 chmod 755
- Files only
- Permissions
-
Clipboard
pbcopy- copies contents of file into your clipboard- Ex:
pbcopy < path/file.txt
- Ex:
pbpaste- allows use of the clipboard in terminal- Ex:
pbpaste > path/file.txt- writes the contents of the clipboard into a file
- Ex:
-
Searching files
grep -[flags] [search-pattern] [target-directory/file](global regular expression print)- Used to search files with matching patterns
-R- search recursively
egrepfind [path] -[option] [query]- Time flags
- By days
-mtimesearches by modification timefind . -mtime 1searches for all files modified exactly 1 day agofind . -mtime -1searches for all files modified within the last dayfind . -mtime +1searches for all files modified more than a day ago
-atimesearches by last accessed time-ctimesearches by last changed time
- By minutes
-cminsearches by last changed time in minutes
- By days
-permsearches by permissionfind . -perm 644finds all files with 644 permissions
-name-inameis case insensitive
-deletewill delete the files found using the find command-typefind [path to install] -type d -exec chmod 755 {} \;will find all directories and change their permissions to755find [path to install] -type f -exec chmod 644 {} \;will find all files and change their permissions to644
xargs- Used to execute other file manipulation commands on the results of a find query
- Place after a find command and separate with |
find . -name "*.tmp" | xargs rm -fto remove .tmp filesfind . -name "*.txt" | xargs grep "text"will find all text files that contain a certain text
- Time flags
-
Search and replace
sed 's/[regex-to-replace]/replacement/ oldfile > newfile'- search and replace- Default behavior is to change only the first matching occurrence of the regex on each line
/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 string- Add
gafter 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 file
perl- From the command line:
perl -i -pe 's/search/replace/g' [filename]-iread from file; use-i.bakor similar to create a backup-edefine perl code to be executed (in '')-padds loops around-ecode- Search and replace options (after the
s/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 search
- Search across multiple lines:
perl -i -pe 'undef $/; s/search/replace/smg' [filename]
- From the command line:
-
File comparison
diff [file1] [file2]to compare files line by line-uunified output (use this unless you have a reason not to)-iignore case-Eignore changes due to tab extension-bignore whitespace changes-wignore all white space-Bignore all lines that are blank
- Creating patches for files
- Use diff to create a patch:
diff -u [original-file] [new-file] > file.patch - Use patch to revert the new file to the original file:
patch -R < file.patch-Rwill reverse the patch-bmakes backups
- Use diff to create a patch:
-
Nano text editor -
nano [filename]-wstart nano with line wrapping off (important for configuration files)- Enable mouse services -
Alt+M - Search
Ctrl + wsearch within a fileAlt + wfind next
- Cut/past
Ctrl + kcut lineCtrl + upaste line- To cut and paste several lines, cut them successively with
Ctrl + kthen paste all withCtrl + u
-
Networking
hostname- find host/domain name and IP address- Displays the local hostname if not given any options
-ddisplays the domain name the machine belongs to-fdisplays the fully qualified host and domain name-idisplays the IP address for the current machine
ping [hostname]- test network connection by sending packets of information to the defined source (also used for testing speed of connection)- Prefix with
doto begin continuous test; useCtrl + Cto stop the test
- Prefix with
ifconfig- get current network adapter configurationnetstat- network connections, including routing tables, interface statistics-gfind all the multicast groups (network) subscribed to this hostnetstat -nap | grep [port-number]- display process id of application which is using the specified port-aor-allwill display all connections including TCP and UDP-rfor routing tables--tcpor-twill display only TCP connections--udpor-uswill display only UCP connections
nslookup [hostname or ip address]- query DNS lookup name- Gets hostname or ip address from given ip address or hostname
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- Changes routing tables to route any ip addresses beginning with
10.208through the VPN connection (PPP0)
- Changes routing tables to route any ip addresses beginning with
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 name
lsof -iscan active ports for local machineiptables*
-
Checksums
md5 [filename]shasum [filename](for SHA1)-ato change to224,256,384, or512
-
Efficiency tips
- Use
![command]to quickly redo the previous command (including flags and arguments) - Use
!!for executing the previous command exactly as typed Ctrl + R + [search]will search for the last command that contains whatever words you typehistory | grep "[keyword]"searches the UNIX command history- Use
|(pipe symbol) to separate multiple commands on the same line - Set up aliases in
.bashrcor.profile - Suspending processes
Ctrl + Zto suspend a processfg [number]orbg [number]to bring suspended processes to the foreground or background
- Use
-
Users
adduser [username]creates new users and prompts you for the detailsuseraddcreates new users and lets you manually specify each option-d /home/usernamespecifies the location of the home directory-mforces the creation of the home directory-g/--gid [group]lets you specify which group to add the user to (checkadduser.confto see what the default is)-G/--groups [group1,group2,etc]for supplementary groups--disabled-passwordprevents password logins (as for when only using SSH keys)
passwd [user]sets the password for a user-lchanges the user's password to an untypable string so it can't be used to login/etc/adduser.conf- Stores user configuration settings
- Ubuntu defaults (change if desired)
- All users added to their own group
- Home user directory permissions set to
755
su [username]will switch to a particular user (useful to become the root user)- Get a list of users -
cat /etc/passwd - Groups
usermod [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-aadds 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 name
deluser [user] [group]will delete that user from the groupgroups [user]will display a list of groups for that usergroupaddandgroupdelto add and remove groups
- Sudo
- Use
sudo visudoto configure which users can use sudo
- Use
- User shells
- The file
/etc/passwdlists each user and determines which shell they run when logged in
- The file
Forked from creativecoder/Unix Command Line Notes.md
Created
November 21, 2016 08:55
-
-
Save jcanfield/fbf72e247a36bc6ed64860fd5b4f4856 to your computer and use it in GitHub Desktop.
Unix Command Line Notes
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment