Notes for my Cloud certifications.
YUM repos are located in /etc/yum.repos.d/. Unlike APT, YUM has several repo files in the folder. Check out the man pages for YUM and the other package management commands.
| command | purpose |
|---|---|
yum update |
updates the repos and gives you the option of updating the packages pending updates |
yum search httpd |
searches for that package |
yum install $package |
to install it |
yum check-update $package |
to see if a package needs any updates |
yum upgrade |
upgrade package |
yum deplist $package |
check package’s list of dependencies |
yum clean packages |
will remove dependencies that were left behind but are no longer needed |
yum remove $package |
removes the package |
yum list installed |
list all installed packages |
| command | purpose |
| — | — |
| rpm -ipv package.rpm | i means install, p means show progress, and v means verbose |
| rpm -q nano | query the package for info (true file name) |
| rpm -qi nano | query the package for more info |
| rpm -e nano | uninstall the package |
| rpm -qR nano | uninstall required packages |
Uses a sources list located in etc/apt/sources.list
| command | purpose |
|---|---|
apt-get update |
searches the online repos and caches the list of packages for when we do a search via… |
apt-cache search $package |
searches for a package in the APT cache |
apt-get install nginx |
install package |
apt-get remove nginx |
remove package |
apt-get remove --purge nginx |
to get rid of config files and such |
apt-get autoremove [$package] |
to remove unneeded packages. |
apt-get upgrade |
upgrades packages |
apt-get -f upgrade |
Imstalls dependencies that we’re flagged while attempting to install a Debian package |
apt-get dist-upgrade |
upgrades the kernel and distribution packages |
| command | purpose |
|---|---|
dpkg -i name.deb |
Installs Debian package |
dpkg --get-selections |
shows all installed packages |
dpkg --remove $package_name |
Removes Debian package |
dpkg --purge $package_name |
Removes dependencies |
Shells are command-line interpreters that accept commands that are then sent to the OS kernel for processing. See list of popular shells I saved as an img on my iPad. You can use any shell installed on the computer by typing its name on the CLI.
Alt + F1 through Alt + F6.echo $SHELLtab
historyhistory 20 show the last 20 commands.!20 execute command # 20!-2 execute the second-to-last command!! execute the previous command!ssh execute the last SSH command!?search? execute the last command with “search” somewhere in it^original^replacement^ find latest command with original and replace that string with replacement on execution.
cat /etc/hots, then ^hots^hosts^Programs only run from inside folders indicated in the $PATH variable and not the working directory.
- are called flags.ls:
-a = all (show hidden files)-l = long listing (type and permissions, number of links the file has, owner, group, size in bytes, date modified)-F = Display a slash after a directory, an asterisk after an executable,-S = sort by file size, descending-r = reverse the sorting to ascending. E.g., ls -lrS
an @ after each symbolic link.-R = recursively display contents of directories.-t = sort by date modified, desc| Command | Purpose |
|---|---|
cd |
change directory. By itself, takes you to your home directory. |
env |
display current user’s environment variables |
halt or init 0 |
shutdown. Note that init works but is deprecated |
ifconfig or ip addr |
shows NIC configs |
netstat |
status of the network |
reboot or init 1 |
restart. Note that init works but is deprecated |
route |
view routing table |
shutdown |
-H= halt; -P= poweroff; c = cancel pending shutdown; r = reboot |
su |
substitute user or super user. E.g., su josue or su - to become root |
top |
list of running apps/processes; top -h gives usage info |
uname |
print OS name. -n = hostname; -r = kernel’s release; -v = kernel’s version number; -m 32- or 64-bit; -p = processor info; -o = full official name of the OS; -a = all info above |
which $program |
full path of the application |
whoami |
current user |
$HISTFILESIZE env variable shows how many lines will be saved in the history file. a value of 0 means save nothing.$HISTCONTROL env variable shows Bash’s history behaviorhistory shows a numbered list of the commands. Rerun a command with !<num>tab key to complete a partially-typed commandDifferent shell use different configuration files. Make sure you know which files your Linux distro uses. A system without a GUI puts you in the login shell. It’s important to know which shell your in so you know which configuration file will be used for it.
/etc/profile. This file sets default variables for all users.~/.bash_profile~/.bash_login~/.profile~/.bashrc/etc/bashrc~/.bash_logout is executed when the user logs out~/.bashrc, which calls /etc/bashrcecho $HOMEenv (not alphabetized) and set (alphabetized)VAR=VALUE. Example, PATH=$PATH:/var/opt/.export $PATH to make that new value available to users in other shells| variable | description |
|---|---|
| LOGNAME | username of current user |
| OLDPWD | previous working directory |
| OSTYPE | duh |
| PATH | distro dependent |
| USER and USERNAME | username of current user |
| HOST and HOSTNAME | system hostname |
| ENV | you can type env or set |
| EUID | UID number of current user |
| HISTFILE | full path of file |
| HISTSIZE | size history can grow to |
- amd _THEDUDE="Jeff Bridges" ; export THEDUDEGlobbing is the process of using wildcards to expand a search. Globbing stands for global command.
* = match 0+ of any character? = match 1 of any character[Aabc] = match any single character in list[^abc] = exclude characters in listls -l ????.txt search for a four-character text filels -l [F]*.txt search for all text files beginning with capital Fls -l f[igh][lfz]e*.txt what you’d expect from regex, except that * matches anything 0+ timesls -l [Rr]eport201[0-9]| Character | Description | Example |
|---|---|---|
" |
allows variable interpolation. | echo "The path is $PATH" |
' |
does not allow variable interpolation | echo 'The path is $PATH' |
\ |
Escapes special chars | echo "You owe \$5.00" |
ls \{enter key} -lah- are called options and switch certain parts of the command on/off. ls -la = ls -l -a- are called arguments.Searches its file database for files or directories the user has access to. Faster than find but doesn’t allow you to indicate the directory.
locate passwd
find $dir [$dir2] {-name | -iname | -size | -mtime | -atime | -ctime}*, ?, and [].
-or -iname "$dir_name" pruneExamples:
find . -iname '*keyword*' # Match keyword
find / -size +1024 # greater than size in bytes
find . -mtime -1 # modified time less than 1 day
find . -atime -1 # accessed time less than 1 day
find . -ctime -1 # created time less than 1 day
find . -iname '*.txt' -or -iname "implementations" -prune
Searches for executables and man page files
whereis cd
man 5 $commandwhatis $command to search for man page entries matching that command. E.g., whatis passwd.apropos $keyword search man pages for entries containing the keyword./ inside a man page to search forward or ? to search backwards... means multiple parameters of that type. E.g., ls -la file1 file2info $topic/usr/doc/packagename/usr/share/doc/packagename/usr/share/doc/packages/packagename/etc directory.rpm -ql passwd | grep doc or rpm -ql yum | grep README| file ext | program used to read them |
|---|---|
.1 - .9 |
man, info, less |
.gz or .bz2 |
gunzip or bunzip2 to decompress, then less to read |
.txt |
any text editor |
.htm, .html |
any web browser, often less |
.odt |
LibreOffice, OpenOffice.org, any word processor |
.pdf |
.xpdf, Adobe Reader |
.tif, .png., .jpg |
Gimp |
The Linux file system and the file system hierarchy standard (FHS)
| directory | description |
|---|---|
| bin | executables necessary to run the OS |
| boot | bootloader files to boot Linux |
| dev | devices that send/receive data sequentially (printers/mice); devices that are block-oriented (HDs, flash drives) |
| etc | text-based config files used by the system |
| home | home folders for users |
| lib -> usr/lib | code libraries for programs in the bin or sbin directories |
| lib64 | 64-bit libraries |
| media | used by some distros to mount external devices |
| mnt | used by some distros to mount other external devices |
| opt | contains files for programs you can install manually |
| proc | pseudo file system for processes |
| root | root user’s home directory |
| sbin | mgmt and config files |
| srv | where services save their files (e.g., httpd) |
| sys | hardware within system |
| tmp | temporary files created by file system |
| usr | application files |
| var | Linux variable data and log files |
touch -d "February 1 2017" file.txt: Allows you to specify the modification timestamp.mkdir -p newdir/newsubdir/newsubdir2: Create a directory and its parents if they don’t exist.rmdir $dir: Can only delete empty directoriescp -puR srcfile dstfile:
p = preserve original ownershipu = update (only if src is newer or dst doesn’t exist)R = recursivemv srcfile directory/: Move/rename file to indicate directorytar command.
-c = create archive-f = read the archive from or write the archive to the specified file-t = list archive’s content w/o extracting it-x = extract tarball-v = verbose output (lists files extracted)-z = compress using gzip-j = compress using bzip2 (like gzip but more resources intensive)Archive (no compression)
| Command | Notes |
|---|---|
tar -cf tarball.tar dir-to-tar |
creates the tarball from dir-to-tar directory |
tar -cf tarball.tar file1 file2 |
creates the tarball from files indicated |
Unarchive (no compression)
| Command | Notes |
|---|---|
tar -tf tarball.tar |
show contents of tarball w/o unarchiving |
tar -xf tarball.tar |
extract tarball |
tar -xvf tarball.tar |
extract tarball, verbose |
Archiving with compression
While not required, it’s best practice to indicate the compression used as part of the file name.
| Command | Notes |
|---|---|
tar -czf tarball.tar.gz dir-to-tar |
use gzip to compress |
tar -cjf tarball.tar.bz2 dir-to-tar |
use bzip2 to compress |
Unarchiving compressed tarballs
| Command | Notes |
|---|---|
tar -xzf tarball.tar.gz |
extract compressed gzipped archive |
tar -xjvf tarball.tar.bz2 |
extract compressed bzip2 archive, verbose |
zip and extract with unzip
zip file.zip file1 [file2] = create a zipped archive of the specified fileszip -r file.zip dir-to-zip
-r is required to go into directories and zip their contents, or else you’ll zip an empty directoryunzip file.zipgzip and extract with gunzip.-c flag, or the -k flag for “keep.”gzip file.tar = will replace original filegzip -c file.tar > file.tar.gz = will keep original file and create file.tar.gzgzip -k file.tar = same as abovegunzip file.tar.gz = uncompress filebzip2 and extract with bunzip. File extension is .bz2bzip2 file.tarbunzip2 file.tar.bz2| Command | Purpose |
|---|---|
cat |
display contents of a file |
less -M |
reads file with pagination. use / to search fwd and ? to search backwards-M shows lines you’re reading and total, plus percentage -N shows line numbers on the left G goes to beginning and shift + G goes to end |
head |
read first 10 lines of a file. -n $num_lines |
tail |
read last 10 lines of a file; -f = follow |
find |
locates file on systemfind . -type d find directoriesfind . -type f find filesfind . -iname "file*. allows globbing |
grep: searches for a string; allows globbing-r = recursive-i = case insensitive-n = show line numbers-w = expression is searched for as wordgrep ^Sirloin file1.txtgrep -i dhcp /var/log/messagesgrep -n dhcp /var/log/messagesgrep -rnw '.' -e 'domo' searches all files in the current folder for the expressionsort: sorts text alphabetically
-r = reverse alphabeticallycut: Remove text from file and print specified fields to stdout
-d = delimiter. E.g., -d" " = space character as the delimiter-f = which field to print (based on the delimiter)cut -d" " -f 6- = start from field 6 through EOLwc: word count. Note that you can specify multiple files.
-w = words-l = lines-c = charsYou can pipe the output of one command as the input for another command:
grep -i republic plato_republic.txt | less
grep -i republic plato_republic.txt | wc -w
grep command| Expression | Description | Example |
|---|---|---|
| * | 0+ repeats of preceding character string or regex | file* |
| . | any single char (grep) | .cc |
| ? | 0+ of proceeding chars | f?le |
| ^ | appears at beginning | ^.b |
| $ | appears at end | ^...$ 3 chars |
\b<needle>\b |
word boundary (must match exactly) | \bwww\b |
| [nnn] | one char btw braces | [abc] |
| [^nnn] | no chars btw braces | [^abc] |
| [a-z] | any single char in range | [a-x] |
| [1-90] | any digit between 1-9, and 0 | `` |
Output is normally displayed on the screen but can be redirected to files or to other commands as input.
tail /var/log/messages > logtemp.txt # redirect stdout
tail /var/log/messages 1> logtemp.txt # same as above
tail /var/log/messages >> logtemp.txt # append
cat bogusfile.txt 2> errors.txt # redirect stderr
cat bogusfile.txt 2>> errors.txt # append
command 1> outfile.txt 2> errfile.txt # redirect to separate files
ctrl + k: cut linectrl + u: paste linectrl + w: search for textctrl + t: spell checkctrl + \: find and replacectrl + g: view helpctrl + x: exitvimtutor = built in tutorial from beginner to advancedi, INSERT, s, o, a:
v = enter visual mode. V = highlights the line; ctrl + V = visual block
y = “yank” or copy highlighted textp = “put” or paste textshift + a = append text at end of lineu = undo last changeh = move leftj = move downk = move upl = move rightdw = delete word under cursordd = deline line under cursor (5dd = delete 5 lines)shift + g = go to bottom of filegg = go to top of file:w = write to disk:wq or x = write to file and quitq! = quit without saving#!/bin/bash = specify an interpreter, (called the shebang)&&: execute command 2 only if command 1 exits normally||: execute command 2 only if command 1 exits abnormally&& and || as such:rm file1.txt && echo "file deleted" || echo "file not deleted"chmod +x <file name>if [ condition ]
then
command
fi
# example
if ["1" == "1"]
then
echo "They are the same"
fi
if [ condition ]
then
command
else
command
fi
# example
if [ "$PWD" == "$HOME" ]
then
echo "You are home."
else
echo "You are in $PWD."
for i in {1..10}
do
echo "$i"
done
#!/bin/bash
# My daily routine script
# If user enters "day", show calendar and date
SHOWDAY=$1
if [ "$1" == "day" ]
then
# Display the calendar
cal
# Display the date/time in UTC
date -u
fi
# Daily greeting
printf "\nHello there, $LOGNAME.\n\n"
if [ "$PWD" == "$HOME" ]
then
echo "You are home."
else
printf "You are in $PWD.\n\n"
fi
# Show us what we have to work on today
DOCUMENTS="/Users/rkumar/Downloads/linux-essentials-practice/text-analysis"
for doc in "$DOCUMENTS"/*.txt
do
echo "$doc"
done
Create the script to set variable values based on args
#! /bin/bash
# list contents of a dir and write the output to a file
# usage: ./findlist.sh $LOCATION $FILENAME
LOCATION=$1
FILENAME=$2
if [ -z "$LOCATION" ]
then
echo "Please provide location argument"
exit 0
fi
if [ -z "$FILENAME" ]
then
echo "Please provide a filename"
exit 0
fi
ls -lh $LOCATION > $FILENAME
echo
echo "Script is complete and indexed $LOCATION."
echo
echo "###########################"
echo "Displaying contents of $FILENAME"
echo "###########################"
cat $FILENAME
| Command | Purpose |
|---|---|
cat /proc/cpuinfo |
view processor details |
free |
view RAM stats in bytes-m = show in MB-g = show in GB |
dmidecode |
show details about motherboard, BIOS, processor, and RAM |
lsblk |
view all block devices (e.g., HDD) attached to system |
df |
view free disk space on HDD-h = human readable format |
du -h $path |
disk usage; human redable, directories only -a = show files |
top |
show stats on processor, RAM, and running processes |
/dev/sda, /dev/sdb, etc.sda1, sda2, etc./proc directory so it can be available to the ps, top, and free commands.ps to identify running processes. Note that this command provides a static snapshot.
-u $username shows processes for that username-e shows every process running from all users-H show hierarchy of processes via indented output. E.g., ps -eH--forest also shows process hierarchy. E.g., ps -e --forest-f shows full format listing (all arguments a command is using while running). E.g., ps -ef --forestps -u josue --forest shows parent/child relationships for processes.ps u U josue gives CPU and memory %.ps aux the u adds the username column. There’s so much output it’s typically more practical to grep.kill -9 $PID will kill a processtop is dynamic, as opposed to ps, which provides a static snapshot.
-h or ? will display CLI usage info and exittop…
k will prompt for the PID of the process to kill.M sort by memory usageP sort by CPU usage (default)free generates a report on the system’s memory status using KB
-h flag shows the information in human-readable measurements (MB, GB)grep sshd /var/log/*dmesg will display messages from the kernel. This helps with tshoot of hardware or driver issues.| Tool | Purpose |
|---|---|
ping -c $num |
testing connectivity |
dig |
dig www.pluralsight.com -t A |
nslookup |
nslookup -query=A www.pluralsight.com |
netstat |
list network connections |
route |
current route/netwk settings |
host $fqdn |
test DNS resolution |
traceroute |
trace packet route |
ifconfig |
current network settings |
ip addr [show] |
current IP addr and network settings |
IPADDR="$addr"`NETMASK="$mask"`NETWORK="$subnet_id"`NETMASKip route show shows the routesroute older method of showing routesnetstat -r same output as the route command, including routes to leave the LANroute add -net $ntwk_id netmask $mask gw $rtr_addrroute del -net $ntwk_id netmask $mask gw $rtr_addrRoute add default gw $ip_addr| Command | Description |
|---|---|
netstat -a |
Lists listening & non-listening sockets |
netstat -i |
Stats about the network interfaces |
netstat -l |
Lists listening sockets |
netstat -s |
Summary for each protocol |
netstat -r |
Equivalent to route |
finger $username gives info on a user (login, directory, name, and shell)id $username gives user ID, group ID, group membershipspwck checks whether passwd and shadow are in sync.pwconv adds any missing users from etc to shadow.su or su - let’s you become Root. su - username gives us a shell as that user, with their PATH var.sudo $cmd is a per-command way to elevate privileges.who = who is logged inW shows logged in users and their processes.who -b last boot timewho -m whostname and user associated with itwho -r our current run levelwho -q number of users logged inwho -a all of the abovelast [$username] who logged in, when, and how, in reverse chronological orderid will show the current user’s UID and GID. You can also type id $usernamegroups $username shows the group memberships.groupadd <grp-name> = add a new groupuseradd [-G $GID] -m -c "John Doe" jdoe = add a new user. This command pulls defaults from /etc/default/useradd
-m = create home dir-c = comment; usually the user’s full nameuserdel -r jdoe = delete user and home foldersudo passwd $username = change user’s password.☁ shell-scripting ll
total 24
drwxr-xr-x 5 rkumar staff 160B May 21 16:22 ./
drwxr-xr-x 5 rkumar staff 160B May 21 08:48 ../
-rwxr-xr-x 1 rkumar staff 546B May 21 16:17 daily.sh*
-rwxr-xr-x 1 rkumar staff 516B May 21 16:22 indexer.sh*
-rw-r--r-- 1 rkumar staff 1.8K May 21 16:22 test1.txt
r = 4w = 2x = 1chmod = change mode of a file or directory, affecting permissions
chmod u=rwx,g=rw,o=r $file_namechmod o-rx daily.sh = remove read and execute permissions from otherschmod -R o-rx shell-scripting/* = recursively alter permissions for files in a directory, but not the directory itself
/* also alters the directory.chmod 600 test1.txt = modify permissions on the file with rw permissions for the user and no permissions for the group or otherschown $file_or_dir = change ownership of a file/directory
chown $username:$group $file
chown $username $filechown :$group $filechgrp = change group ownership of a file/directoryln -s $src_name $link_name one convention is to append .lnk to the end of the symlink nameunlink $link_name removes the symlinkls -l output.ln $src_file $link_namels -ld /tmp, which gives drwxrwxrwt. 8 root root 211 May 23 18:22 /tmpchmod o+t $dir_namechmod 1777 $dir_name the 1 denotes the sticky bit. To remove it, use chmod 777 $dir_name, where the absence of the 1 implies a zero (chmod 0777 $dir_name)