-A Linux distribution is comprised of the Linux kernel and additional software
- https://DistroWatch.com
- Red Hat Enterprise Linux (RHEL)
- Fedora
- Ubuntu
- Debian
- SuSE Linux Enterprise Server (SLES)
- OpenSuSE
/
: “Root,” the top of the file system hierarchy./bin
: Binaries and other executable programs./etc
: System configuration files./home
: User home directories./opt
: Optional or third party software./tmp
: Temporary space, typically cleared on reboot./usr
: User related programs./var
: Variable data, most notably log files./var/logs
/usr/local
/opt
jason@linuxsvr ~]$
normal user[root@linuxsvr:~]#
super user~jason
= /home/jason~pat
= /home/pat~root
= /root~ftp
= /srv/ftpls
: Lists directory contents.
-l
: long listing formatcd
: Changes the current directory.pwd
: Displays the present working directory.cat
: Concatenates and displays files.echo
: Displays arguments to the screen.man
: Displays the built-in manual.man -k calendar
: search manual pages using keywordspace
: display the next pageenter
: move down one lineg
: go to top of pageG
: go to bottom of pageq
: quittouch
: Craete new file or update time stamp of existing file exit
: Exits the shell or your current session.clear
: Clears the screen.--help
or -h
$PATH
controls your search pathecho $PATH
: view content of \$PATH variable/full/path/to/command
./command-in-this-dir
which cat
: locate the command cat
.
This directory..
The parent directorycd -
Change to the previous directorypwd
Show present working directoryecho $OLDPWD
: view directory you pervious endmkdir [-p] directory
-p
to create multiple directoriesrmdir [-p] directory
rm -rf directory
ls -l
: Show long listing format
-rw-rw-r-- 1 jason users 10400 Sep 27 08:52 sales.data
ls -a
: Show hidden files.
ls -l -a
is the same as ls -la
and ls -al
ls -F
: Show file types (at the end)/
: Directory@
: Link*
: Executablels -t
: List file by timels -r
: Reverse orderls -latr
: Long listing including all files reverse sorted by timels -R
: List files recursivelytree -d
: List directories onlytree -C
: Colorize outputls --color
: Colorize the output-
_
ls -l "my notes.txt"
or ls -l 'my notes.txt'
Type
$ls -l
-rw-rw-r-- 1 jason users 10400 Sep 27 08:52 sales.data
Symbol | Type |
---|---|
- | Regular file |
d | Directory |
\ | Symbolic link |
r | Read |
w | Write |
x | Execute |
Permission | File | Directory |
---|---|---|
Read (r) | Allows a file to be read. | Allows file names in the directory to be read. |
Write (w) | Allows a file to modified. | Allows entries to be modified within the directory. |
Execute (x) | Allows the execution of a file | Allows access to contents and metadata for entries. |
Permission Categories
u
: Userg
: Groupo
: Othera
: AllGroups
groups [userId]
command displays a user’s groups.id -Gn
Changing Permissions
chmod
: Change mode (permission) commandchmod g+w sales.data
chmod g-w sales.data
chmod g+wx sales.data
chmod u+rwx, g-x sales.data
chmod a=r sales.data
chmod u=rwx, g=rx, o= sales.data
Numeric Based Permissions
r | w | x | |
---|---|---|---|
0 | 0 | 0 | Value for off |
1 | 1 | 1 | Binary value for on |
4 | 2 | 1 | Base 10 value for on |
chmod 754 sales.data
666
or 777
Working with Groups
chgrp
command changes the groupchgrp sales sales.data
File Creation Mask
777
for directories666
for filesThe umask Command
umask [-S] [mode]
-S
: return symbolic notationumask -S
returns u=rwx, g=rx, o=rx
for .
mode
: octal value '755', '664' etcOctal subtraction
Common umask modes
022
002
077
007
umask
without any arguments, it will display the mode in 4 characters instead of the 3 that we're working with:umask
returns 0022
(same as umask 022)Displaying Contents of Static Files
cat file
: Display the contents of file.more file
: Browse through a text file.less file
: More features than more
(less is more).head file
: Output the beginning (or top) portion of file.-n
e.g. head -15 file.txt
tail file
: Output the ending (or bottom) portion of file.-n
e.g. tail -15 file.txt
Viewing Files in Real Time
tail -f file
: Displays data as it is being written to the file e.g. log fileNano Editor
nano file.txt
vi [file]
: Edit filevim [file]
: Same as vi, but more featuresview [file]
: Starts vim in read-only modeMode | Key |
---|---|
Command | Esc |
Insert | iIaA |
Line | : |
Vi Command Mode and Navigation
esc
keyk
: Up one line.j
: Down one line.h
: Left one character.l
: Right one character.
w
: Right one word.b
: Left one word.^
Go to the beginning of the line.$
: Go to the end of the line.Vi Insert Mode
i
: Insert at the cursor position.I
: Insert at the beginning of the line.a
: Append after the cursor position.A
: Append at the end of the line.Vi Line Mode
:
:w
: Writes (saves) the file.:w!
: Forces the file to be saved.:q
: Quit.:q!
: Quit without saving changes.:wq!
: Write and quit.:x
: Same as :wq
.:n
: Positions the cursor at line n.:15
: Go to line 15 of the file:$
: Positions the cursor on the last line.:set nu
: Turn on line numbering.:set nonu
: Turn off line numbering.:help [subcommand]
Get help.Vi Repeating Commands
5k
: Move up a line 5 times80i<Text><ESC>
: Insert 80i_<Esc>
: Insert 80 "_" charactersVi Deleting Text
x
: Delete a character.dw
: Delete a word.dd
: Delete a line.D
: Delete the remaining text from the current position.Vi Changing Text
r
: Replace the current character.cw
: Change the current word.cc
: Change the current line.c$
: Change the text from the current position.C
: Same as c$.~
: Reverses the case of a character.Vi Copy and Paste
yy
: Yank (copy) the current line.y<position>
: Yank the yw
: Yank a word y3w
: Yank three wordsp
: Paste the most recent deleted or yanked text.Vi Undo/ Redo
u
: UndoCtrl-R
: RedoVi Searching
/<pattern>
: Start a forward search.?<pattern>
: Start a reverse search.n
: Go to the next matchN
: Go to the previous matchVi Tutor
vimtutor
: VIM TutorCtrl
while pressing <char>.alt
key) while pressing <char>.Esc
, then type C-h
: HelpC-x C-c
: ExitC-x C-s
: Save the fileC-h t
: Built-in tutorialC-h k <key>
: Describe keyEmacs Navigation:
C-p
: Previous line.C-n
: Next line.C-b
: Backward one character.C-f
: Forward one character.M-f
: Forward one word.M-b
: Backward one word.C-a
: Go to the beginning of the line.C-e
: Go to the end of the line.M-<
: Go to the beginning of the file.M->
: Go to the end of the file.Emacs Deleting Text
C-d
: Delete a character.M-d
: Delete a word.Emacs Copy & Paste, Undo
C-k
: Kill (cut)C-y
: Yank (paste)C-x u
: UndoEmacs Searching
C-s
: Start a forward search.C-r
: Start a reverse search.Emacs Repeating Commands
C-u N <command>
: Repeat <command> N times.The find Command
find [path...] [expression]
-name pattern
: Find files and directories that match 'pattern'.-iname pattern
: Like '-name', but ignores case.-ls
: Performs an 'ls' on each of the found items.-mtime days
: Finds files that are 'days' old.-size num
: Finds file that are of size 'num'.-newer file
: Finds files that are newer than 'file'.-exec command {} \;
: Run 'command' against all the files that are found.find /bin -name *v
find . -mtime +10 -mtime -13
: find files that are more than 10 days old but less than 13 days old in current directoryfind s* -ls
find . -size +1M
: find files that are more than 1MBfind . -type d -newer file.txt
: find directories that are newer than 'file.txt'find . -exec file {} \;
: excute 'file' command on all search resultfile
command tells you the file typeA Fast Find - Locate
locate pattern
find
command.emacs
: Emacs has a graphical mode too.gedit
: The default text editor for Gnome.gvim
: The graphical version of vim.kedit
: The default text editor for the KDE.AbiWord
: Microsoft Word alternative.LibreOffice
: Full office suite.Application > Office
Kate
: Source code editor.Applications > Accessories
Removing Files
It's a good idea to use ls
command to check file to be remove before acutally removing it
rm file
: Remove file.
rm -r dir
: Remove the directory and its contents recursively.rm -f file
: Force removal and never prompt for confirmation.Copying Files
cp source_file destination_file
: Copy source_file to destination_file.cp src_file1 [src_fileN ...] dest_dir
: Copy source_files to destination_directory.cp -i
: Run in interactive mode.cp -r source_directory destination
: Copy src_directory recursively to destination.Moving and Renaming Files
mv
: Move or rename files and directories.mv source destination
mv -i source destination
: Interactive modeSorting Data
sort file
: Sort text in file.-k F
: Sort by key. F is the field number.sort -u -k2 more-secrets
: sort by the second column in file 'more-secrets'-r
: Sort in reverse order.-u
: Sort unique.Creating Archives (tar)
tar [-] c|x|t f tarfile [pattern]
tar
doesn't need the hyphen -
before optionsc
: Create a tar archive.x
: Extract files from the archive.t
: Display the table of contents (list).v
: Be verbose.z
: Use compression.f file
: Use this file.tar cf tps.tar tpsreports
tar tf tps.tar
tar xf /home/test/tps.tar
: extract filestar xvf /home/test/tps.tar
: extract files in verboseCompressing Files to Save Space
gzip
: Compress files..gz
in the file namegunzip
: Uncompress files.gzcat
or zcat
: Concatenates compressed files.Using gzip + tar
tar zcf test.tgz tpsreports
: Compress tartar zcf test.tar.gz tpsreports
: Compress tartgz
, tar.gz
tar ztvf tpsreports
: View contents of gzip filesdu
: Estimates file usage.du -k
: Display sizes in Kilobytes.du -h
: Display sizes in human readable format.ls
rm
cp
*
: matches zero or more characters.?
: matches exactly one character.[]
: A character class.[aeiou]
: start with a vowelca[nt]*
[!]
: Matches any of the characters NOT included between the brackets. Matches exactly one character.[!aeiou]*
: NOT starts with a vowelWildcards Ranges
-
to create a range in a character class.[a-g]*
[3-6]*
Predefined named character classes
[[:alpha:]]
: Matches alphabetical letters (upper and lower cases letters)[[:alnum:]]
: Matches alpha numeric characters[[:digit:]]
ls *[[:digit:]]
: find files that end with a digit[[:lower:]]
[[:space:]]
: Matches spaces, tabs, new line characters
[[:upper:]]
Matching Wildcard Patterns
\
: escape character. Use if you want to match a wildcard character.*\?
I/O Name | Abbreviation | File Descriptor |
---|---|---|
Standard Input | stdin | 0 |
Standard Output | stdout | 1 |
Standard Error | stderr | 2 |
Redirection
>
: Redirects standard output to a file.ls -l 1> files.txt
is the same as ls -l > files.txt
>>
: Redirects standard output to a file.<
: Redirects input from a file to a command.sort < files.txt
sort files.txt
&
: Used with redirection to signal that a file descriptor is being used.2>&1
: Combine stderr and standard output.2>file
: Redirect standard error to a file.sort < files.txt > sorted_files.txt
The Null Device
>/dev/null
: Redirect output to nowhere.ls 2> /dev/null
: Redirect stderr to nowhere (not display on screen)ls here not-here > /dev/null 2>&1
: Append stderr to stdoutputComparing the Contents of the Files
diff file1 file2
: Compare two files.sdiff file1 file2
: Side-by-side comparison.vimdiff file1 file2
: Highlight differences in vim.diff Output
LineNumFile1-Action-LineNumFile2
$diff file1 file2
3c3
< this is a line from file1
---
> This is a line from file2
sdiff Output
$ sdiff file1 file2
line in file1 | line in file2
> more in file2
|
: Differing lines<
: Line from file 1 (only exist in file 1)>
: Line from file 2 (only exist in file 2)vimdiff
Ctrl-w w
: Switch between windows:q
: Quit (close current window):qa
: Quit all (close both files):qa!
: Force quit allThe grep Command
grep
: Display lines matching a pattern which is case sensitive.grep pattern [file]
-i
: Perform a search, ignoring case.-c
: Count the number of occurrences in a file.-n
: Precede output with line numbers.-v
: Invert Match. Print lines that don’t match.The file Command
file [file_name]
: Display the file type of 'file_name'.$ file sales.data
sales.data: ASCII text
$ file *
bin: directory
jason.tar: POSIX tar archive
Searching for Text in Binary Files
strings
: Display printable stringsPipes
|
command-output | command-input
cat file | grep pattern
grep pattern file
strings giant-steps.mp3 | grep -i john | head -1
strings giant-steps.mp3 | grep -i john | head -1 | cut -d' ' -f2
The cut command
cut [file]
: Cut out selected portions of file. If file is omitted, use standard input.-d delimiter
: Use delimiter as the field separator.-f N
: Display the Nth field.Searching and Pipe Example
/etc/passwd
contains all accounts in a Linux systemgrep bob /etc/passwd
grep bob /etc/passwd | cut -d: -f1,5
grep bob /etc/passwd | cut -d: -f1,5
| sortgrep bob /etc/passwd | cut -d: -f1,5 | sort | tr ":" " "
tr "char1" "char2"
: Translate a character into another charactergrep bob /etc/passwd | cut -d: -f1,5 | sort | tr ":" " " | column -t
column -t
: Format output in table formatPiping Output to a Pager
cat /etc/passwd | less
less /etc/passwd
Copying Files over the Network
SCP
- Secure copySFTP
- SSH file transfer protocolCommand Line SCP Clients
Graphical SCP/SFTP Clients
scp / sftp command line utilities
scp source destination
: Copy source to destination.sftp host
: Start a secure file transfer session with host.sftp jason@host
ftp Command Line Utility
ftp host
: Start a file transfer session with host.Example: SFTP
sftp linuxsvr
: Connect to serverpwd
: When you connect to the remote server, you're placed into your home directoryl
, that's for locallpwd
lls
: Show what files are on the local boxput z.txt
: Upload file to remote serverquit
: Disconnect from remote serverExample: SCP
scp z.txt linuxsvr:/tmp/
: Upload file to 'tmp' directory in the remote serverscp z.txt linuxsvr:~/
: Upload file to remote home directoryssh linuxsvr
: Connect to the remote serverscp z.txt adminuser@linuxsvr:/home/adminuser/
: Transfer file to remote server as a different usersftp adminuser@linuxsvr
: Connect to remote serverCustomizing the Shell Prompt
$PS1
.$prompt
.\d
: Date in "Weekday Month Date" format "Tue May 26"\h
: Hostname up to the first period\H
: Hostname (full domain name)\n
: Newline\t
: Current time in 24-hour HH:MM:SS format\T
: Current time in 12-hour HH:MM:SS format\@
: Current time in 12-hour am/pm format\A
: Current time in 24-hour HH:MM format\u
: Username of the current user\w
: Current working directory\W
: Basename of the current working directory\$
: If the effective UID is 0 (root), a #
, otherwise a $
.bash_profile
echo 'export PS1="[\u@\h \w]\$ "' >> ~/.bash_profile
quit
: Log outssh linuxsvr
: Log back inecho $PS1
: Check the current prompt stringPS1="\u@\h \$"
: Customize prompt stringcabox@box-codeanywhere$
PS1="<\t \u@\h \w>\$"
<10:30:16 cabox@box-codeanywhere ~/workspace>$
cd /var/log
PS1="\d \t \h \W>\$"
Sun Feb 23 09:23:51 linuxsvr log>$
Shell Aliases
alias [name[=value]]
alias
: List aliases setname=value
to create new aliasalias grpe='grep'
alias cls='clear'
unalias name
: Remove the “name” alias.unalias -a
: Remove all aliases.bash_profile
alias ll='ls -l'
Can change how an application behaves
man
pagesViewing Environment Variables
printenv
: Print all or part of environment.printenv HOME
: Print the HOME variableecho $ENV_VAR
: Print the ENV_VAR variable.$
when using echo
Creating Environment Variables
export VAR="value"
export EDITOR="vi"
export TZ="US/Pacific"
Removing Environment Variables
unset VAR
unset TZ
Persisting Environment Variables
.bash_profile
Common Environment Variables
EDITOR
: Program to run to perform editsHOME
: Home directory of the user.LOGNAME
: The login name of the user.MAIL
: The location of the user’s local inbox.OLDPWD
: The previous working directory.PATH
: A list of directories to search for commands.PAGER
: Program used to paginate through files.PS1
: The primary prompt string.PWD
: Present working directory.USER
: The username of the current user.Listing Processes and Information
ps
: Display process status.-e
: Everything, all processes.-f
: Full format listing.-u username
: Display username’s processes.-p pid
: Display information for PID.ps -e
: Display all processes.ps -ef
: Display all processes, full.ps -eH
: Display a process tree.ps -e --forest
: Display a process tree.ps -u username
: Display user’s processes.Other ways to view processes
pstree
: Display processes in a tree format.top
: Interactive process viewer.htop
: Interactive process viewer.Background and Foreground Processes
command &
: Start command in background.Ctrl-c
: Kill the foreground process.Ctrl-z
: Suspend the foreground process.bg [%num]
: Background a suspended process.bg
will operate on current job i.e. the last job that was stopped while it was in the foreground, or the last job that was started in the background%%
or %+
%-
fg [%num]
: Foreground a background process.kill [%num]
: Kill a process by job number or PID.jobs [%num]
: List jobs.jobs %%
: List current jobjobs %+
: List current jobCtrl-c
: Kills the foreground proc.kill [-sig] pid
: Send a signal to a process.kill 123
kill -15 123
kill -TERM 123
-TERM
can't kill, use kill -9 123
kill -l
Display a list of signals.Cron & Crontab
cron
service runs scheduled jobscrontab
command to schedule jobsCrontab Format
* * * * * command
| | | | |
| | | | +-- Day of the Week (0-6)
| | | +---- Month of the Year (1-12)
| | +------ Day of the Month (1-31)
| +-------- Hour (0-23)
+---------- Minute (0-59)
Redirecting Output
0 2 * * * /root/backupdb > /tmp/db.log 2>&1
: Run at 02:00 every day and send output to a log file.Example Crontab Entry:
0 7 * * 1 /opt/sales/bin/weekly-report
: Run every Monday at 07:00.0,30 * * * * /opt/acme/bin/half-hour-check
: Run every 30 minutes.*/2 * * * * /opt/acme/bin/half-hour-check
: Another way to do the same thing.0-4 * * * * /opt/acme/bin/first-five-mins
: Run for the first 5 minutes of the hour (run 5 times every hour)Crontab Shortcuts
man cron
to check if this works for you@yearly
0 0 1 1 *@annually
0 0 1 1 * @yearly
@monthly
0 0 1 * *@weekly
0 0 0@daily
0 0 * * *@midnight
0 0 * * *@daily
@hourly
0 * * * *Using the Crontab Command
crontab
command manipulates cron jobscrontab file
: Install a new crontab from file.crontab -l
: List your cron jobs.crontab -e
: Edit your cron jobs.crontab -r
: Remove all of your cron jobs. The su Command
su [username]
: Switch usersu Options
-
: A hyphen is used to provide an environment similar to what the user would expect had the user logged in directly.su - userB
option-c command
: Specify a command to be executed.su -c 'echo '$ORACLE_HOME' - oracle
Who Am I?
whoami
: Displays your account name.$whoami
jason
$ su oracle
Password:
$ whoami
oracle
$
sudo
: Execute a command as another user, typically the superuser.sudo
over the su
command is that you don't need to know the password of the other user. If the sudo configuration permits access, that command is executedsudo -l
: List available commands.sudo command
: Run command as root.sudo -u root command
: Same as sudo command
.sudo -u user command
: Run as user.sudo su
: Switch to the superuser account.sudo su -
: Switch to the superuser account with root’s environment.sudo su - username
: Switch to the username account.sudo -s
: Start a shellsudo -u root -s
: Same as sudo -s
sudo -u user -s
: Start a shell as uservisudo
: Edit the /etc/sudoers
fileuser host=(users) [NOPASSWD:]commands
adminuser ALL=(ALL) NOPASSWD:ALL
jason linuxsvr=(root) /etc/init.d/oracle
Shell History
~/.bash_history
~/.history
~/.histfile
history Command
history
: Display the shell history.HISTSIZE
: Controls the number of commands to retain in history.export HISTSIZE=1000
: Increase history size! Syntax
!num
: Repeat command line number 'num'.history
to view the line number!
is called "bang"!!
: Repeat the previous command line.!string
: Repeat the most recent command starting with "string."!^
: Represents the first argument!^
= !:1
!$
: Represents the last argument
Pulling Out Words from Previous Command
!:num <Event> <Separator> <Word>
!
: Represents a command line (or event).!
: The most recent command line!=!!
:num
: Represents a word on the command line0
: command1
: first argument, etc.$ head files.txt sorted_files.txt notes.txt
<output from head command here>
$ !!
head files.txt sorted_files.txt notes.txt
<output from head command here>
$vi !:2
vi sorted_files.txt
<vi editor starts>
$ls !^
ls files.txt
<output from ls here>
$ls !$
ls notes.txt
<output from ls here>
Searching Shell History
Ctrl-r
: Reverse shell history searchCtrl-r
again to get to next matchEnter
: Execute the commandArrows
: Change the commandCtrl-g
: Cancel the searchAuto Completion
Tab
: Perform auto completionTab+Tab
: View all the possible completion optionsls -ld ~
: list current user home directoryls -ld ~adm
: list user home directory starts with 'adm'Package
Package Manager
sudo
or su
to the "root" user if sudo
is not configuredInstalling Software on RPM Distros
RPM
stands for "Redhat Package Manager"yum
command line utility is a package management progrm for those Linux distributions that use RPM packagesyum search string
: Search for package containing 'string'yum info [package]
: Display infoyum install [-y] package
: Install package-y
to automatically reply 'yes' to yum's questionsyum remove package
: Remove packagerpm -qa
: List all installed packages.rpm -qf /path/to/file
: List the file’s package.rpm -ql package
: List package’s files.rpm -ivh package.rpm
: Install package.rpm -e package
: Erase (uninstall) package.Installing Software on DEB Distros
DEB
stands for "Debian"APT
stands for "Advanced Packaging Tool"apt-cache search string
: Search for package with 'string'.apt-get install [-y] package
: Install package.-y
to automatically reply 'yes' to apt-get's questionsapt-get remove package
: Remove package, leaving configuration.apt-get purge package
: Remove package, deleting configuration.apt-cache show package
: Display information about package.dpkg -l
: List installed packages.dpkg -S /path/to/file
: List file’s package.dpkg -L package
: List all files in package.dpkg -i package.deb
: Install package.Make sure that the network adaptor is set to "Bridged"
Starts the VM
Make sure that a ssh-server
is installed and running
ps -ef | grep sshd
: Check process table and search for SSH daemon / SSH server processThe results show that sshd
is not running
Check if ssh-server
is installed
dkpg -l | grep ssh-server
rpm -qa | grep ssh-server
If not found, install ssh-server
sudo apt-get update
sudo apt-get install openssh-server openssh-client
openssh-client
is used to connect to other system from this systemsudo yum install openssh-server openssh-client
Look at the process table and check for sshd
, make sure it's running
ps -ef | grep sshd
You can see that it's up and running
If not running, use
sudo service ssh start
sudo service sshd start
Get the IP address of this VM
/sbin/ip addr
Note there are 2 network interfaces
loopback device
which allows the system to communicate with itself127.0.0.1
10.0.0.6
in the 2nd network interfaceConfirm username
whoami
Connect to VM using Terminal
ssh adminuser@10.0.0.6
: Login VMexit
: Exit VMputty
: Starts putty