Take control of Linux Flashcards
$ sudo [command]
For every command that requires root permission.
$ sudo su
Same as putting sudo in front of a command.
$ pwd
print working directory , or “where I am”.
$ ls
List the content of the current directory.
$ ls -a
List the content of the working directory, including hidden files.
$ cd [directory]
Change the current directory.
$ cd ..
Move to parent directory of current directory.
$ mkdir [directory]
Create a directory.
$ cp [source] [destination]
Copy and paste a file.
$ mv [source] [destination]
Move (rename) a file or directory.
$ cp -r [source] [destination]
$ Copy and paste a directory.
$ rm [file]
Remove file.
$ rm -rf [directory]
Recursive removal of directory.
$ cat [file]
cat means “concatenate”. View the content of a file.
$ cat [file] [file]
View the content of multiple files.
$ cat >[file]
Create a file.
$ cat [file1] > [file2]
Redirect standard output of file1 into new file2. Existing content of file2 will be overwritten.
$ cat [file1] >> [file2]
Append standard output of file1 into file2, without overwritting.
$ cat < [file]
Output of the file will be shown in terminal.
$ cd (or $ cd ~)
Navigate to home directory.
$ cd /
Navigate to root directory.
$ cd -
Navigate to previous directory.
$ ln -s [target] [source]
Create a symbolic link at [source] referencing the original file [target].
What is a symbolic link?
Also called soft link or symlink, it can be thought of as a shortcut to a file or directory.
$ stat [file_or_dir]
Display file status.
$ stat -c %a [file_or_dir]
Display access rights in octal (numeric) of file.
What are the different classes of users for file access?
owner: #– or -###—— group: -#- or —-###— other: –# or ——-###
What are the different permissions for file access?
read: 4 or r write: 2 or w execute: 1 or x
How to change permissions with letters? Example: add other & execute.
+: add permission. -: remove permission. =: set permission. Example: chmod o+wx [file]
$ ls -l [file]
Display access rights of file in letters.
How to change permissions with numbers? Example: -rw-rw-rwx.
Add the value of each permissions you want to set for each group. Example: owner: 4+2=6 group: 4+2=6 other: 4+2+1=7 $ chmod 667 [file]
$ sudo chown [username]:[group] [directory]
Change the ownership of both the user and the group for this directory.
$ sudo chown -R [username]:[group]
Change the ownership of both the user and the group of all files and directories within this directory.
How to make root the only user able to write the file?
$ sudo chown root:root [file] $ sudo chmod 700 [file]
What is the command apt-get?
apt is one of the tools used to interact with the APT (Advanced Packaging Tool) to install, remove and manage packages in Debian-based Linux distributions.
What is the command apt?
apt consists of some of the most widely used features from apt-get and apt-cache leaving aside seldom used features. It is considered more secure to use apt.
$ tail [file]
View the last 20 lines of a file.
$ tail -n [number]
View an arbitrary number of the most recent files.
$ tail -f [file]
Follow a file as more lines get appended to it.
$ apt-get update
Update the list of available packages and their versions, but do not install or upgrade any package.
$ apt-get upgrade
Actually installs newver versions of the packages. To be used after having updated the package lists.
$ apt-get install [package]
Install a new package.
$ apt-get check
Does an update of the package lists and checks for broken dependencies.
$ apt-get autoclean
Removes .deb files for packages that are no longer install on the system.
$ apt-get clean
Remove all packages from the package cache (more powerfull than apt-get autoclean).
$ apt-get remove [package]
Removes an install package, leaving the configuration file intact.
$ apt-get purge [package]
Completely removes an installed package and the associated configuration files.
$ apt-get autoremove
Remove packages that were installed by other packages and are no longer needed.
$ apt-cache search [search_term]
Lists packages whose name or description matches search term.
$ apt-cache show [package]
Shows description of package as well as version, size, dependencies and conflicts.
$ man apt-get (or apt-cache or dpkg)
Shows the manual associated with these tools.
With apt-get, for what the -s flag is used for?
To simulate an action. Example: apt-get -s install [package] will simulate installing the package, showing what will be installed and configured.
What is Zsh?
An alternative shell to the traditional Bash (Bourne Again Shell) with syntax highlighting, tools integration and plugins.
chsh -s /bin/zsh
Make Zsh the default shell.
What are two popular plugin managers for Zsh?
oh-my-zsh and zprezto.
What is tmux? What is it usefol for?
tmux is a terminal multiplexer, allowing a user to access multiple separate terminal sessions inside a single terminal window or remote terminal session. It is useful for dealing with multiple programs from a command-line interface, and for separating programs from the Unix shell that started the program.
$ tmux
Start a tmux session.
How are commands triggered in tmux?
By a prefix key (C-b or Ctrl+b) followed by a command key.
C-b %
Split a tmux pane into a left pane and right pane.
C-b “
Split a tmux pane into a top pane and bottom pane.
C-b
Navigate panes in tmux.
$ exit or C-d
Close a pane in tmux.
C-b c
Create a new window in tmux, similar to creating a new virtual desktop.
C-b p / C-b n
Navigate to previous or to next window in tmux.
C-b
Navigate to a specific window in tmux, given its number.
C-b d
Detach current session in tmux and leave it running in the background for later reuse.
$ tmux ls
Figure out which sessions are running in the background, possibly to attach to them.
$ tmux attach -t [number]
Attach to a tmux session with a given number.
$ tmux new -s [name]
Start a tmux session with a given name.
$ tmux rename-session -t [old number or name] [name]
Rename a tmux session.
What does it mean that the text editor Vim is modal?
The actions we can perform in Vim depends of the mode we are using.
What are the 3 modes of Vim?
Insertion mode: similar to a classic editor, the text typed is inserted where the cursor is. Normal/Command mode: enable text navigation, copy-pastes, deletions… Visual mode: enable text selections.
What is a Vim plugin managers and some of its absolutely necessary plugins?
Plugin manager: Vundle. Plugins: NERDtree (file hierarchy), ack (search for a character chain), CtrlP (fuzzy search of files), Surround (add/modify quotes, double quotes, parentheses…)
$ vim [file]
Edit a file or create a new file if it does not exist yet.
In Vim: i
Enter insertion mode before the current position.
In Vim (insertion): ESC
Enter command mode.
In Vim: :wq
Save the file (Write) and then quit Vim.
In Vim: :q!
Quit and discard changes.
How to enter a command in Vim?
Hit the semicolon key :.
In Vim (command): :q
Quit without discard changes.
How to move within Vim?
Either use the arrow keys, or use the following keys: h: left j: down k: up l: right
In Vim (command): x
Delete a character from command mode.
In Vim: a
Enter insertion mode after the current position.
In Vim: o
Enter insertion mode below the line.
In Vim: O
Enter insertion mode above the line.
What is the format of a command in Vim?
[operator][number][motion]
In Vim: d
Delete operator (acts like a “cut” command).
In Vim: c
Change operator.
In Vim: r
Replace operator.
What is the w motion in Vim?
Until the start of the next word, excluding its first character.
What is the e motion in Vim?
To the end of the current word, including the last character.
What is the $ motion in Vim?
To the end of the line, including the last character.
What are counts in Vim?
Counts are optional and let you put a multiplier to your command and motion.
In Vim: dw
Delete a word. If in the middle, it will stop where the word ends.
In Vim: d$
Delete to end of line.
In Vim: u
Undo command.
In Vim: G
Move to the bottom of a file.
In Vim: gg
Move to the start of a file.
In Vim: Ctrl+g
View current cursor position.
In Vim: +G
Jump to a specific line.
In Vim: /
Search a page after the cursor position.
In Vim: ?
Search a page before the cursor position.
In Vim: n
Navigate to the next search match.
In Vim: N
Navigate to the previous search match.
In Vim: %
For ( and ), [and], { and }, move the cursor to the matching counter part.
In Vim: :s//
Find and replace the first instance of word1 by word2.
In Vim: :s///g
Find and replace all instances of word1 by word2.
In Vim: dd
Cut a line.
In Vim: diw
Cut a word.
In Vim: daw
Cut a word and all spaces after it. If there are no spaces after it, delete the spaces before it.
In Vim: v
Select characters.
In Vim: V
Select whole lines.
In Vim: Ctrl-v
Select rectangular blocks.
In Vim: y
Copy (or “yank”) operator.
In Vim: yy
Copy whole line.
In Vim: p
Paste after cursor operator
In Vim: P
Paste before cursor operator.
In Vim: yiw
Copy current word excluding surrounding spaces.
In Vim: yaw
Copy current word including leading or trailing spaces.
In Vim: I
Enter insertion mode at the start of the current line.
In Vim: a
Enter insertion mode after the current position.
In Vim: A
Enter insertion mode at the end of current line.
In Vim: ciw
Cut current word excluding surrounding spaces and enter insertion mode at the same position.
In Vim: caw
Cut current word including leading or trailing spaces and enter insertion mode at the same position.
$ git init
Initialize a git repository.
$ git status
See current state of project.
$ git add [file]
Add a file to the staging area to start tracking changes.
$ git commit -m “[message]”
Store the staged changes in the repository.
$ git log
Display the history of commits.
$ git remote add [remote_name] [repository_URL]
Push local repo to the GitHub server where a new empty GitHub repository was created beforehand.
$ git push -u [remote_name] master
Push the local repository to the [remote_name] repo with default local branch name being master. The -u tells Git to remember the parameters for the next time.
$ git pull [remote_name] master
Pull down any new changes to the master branch.
$ git diff HEAD
After pulling new changes, check what is different from our last commit using the HEAD pointer.
$ git diff –staged
Check what is different from our last commit compared to the changes we just staged.
$ git reset [file]
Remove file from staging area.
$ git checkout – [file]
Change the file back to how it was at the last commit.
What is a repository?
A directory where Git has been initialized to start version controlling the files.
What are the different file statuses in Git?
Staged: files are ready to be commited. Unstaged: files with changes and not prepared to be commited. Untracked: not tracked by Git yet. Usually new files. Deleted: file has been deleted and is waiting to be removed from Git.
$ git add -A .
Add all files to staged area. The dot stands for current directory. The -A ensures even file deletions are included.
What is a git commit?
A snapshot of a repository to which we can come back if we ever need to.
$ git log –summary
See more information for each commit, such as where new files were added for the first time or where files were deleted.
What is the use of Git hooks for a webserver?
Upload directly to a webserver whenever you push to the master remote instead of having to upload the site with an FTP client.
$ git stash
Sometimes when you oull, you may have changes you do not want to commit. Before you pull, stash your changes.
$ git stash apply
Re-apply stashed changes after you pull.
$ In git, where does the HEAD pointer points to and what does it hold?
By default HEAD points to the most recent commit. HEAD holds your position within all the different commits.
What does the – mean in Git?
It promises the command line that there are no more options after the –. Example: useful to checkout (revert) a file instead of switching to a branch with the same name.
$ git branch [name]
Create a copy (branch) of the repo, to later be merged back into the main master branch.
$ git branch
List all the branches of our repo.
$ git checkout [branch_name]
Switch to a different branch.
$ git rm [file]
Remove files from the system as well as stage the removal of the files.
How to use wildcards in Git?
Wildcards need to be enclosed by quotes. Example: $ git rm ‘*.txt’
What should we do in got when working on multiple features?
Separate the code base into multiple branches to work on and commit separately.
$ git checkout -b [name]
Checkout and create a branch at the same time.
$ git rm -r [directory]
Recursively remove all folder and files from the given directory in our repository.
$ git commit -am “[message]”
Auto remove deleted files with the commit, without having to $ git rm the files (simply $ rm them).
What is a pull request?
A pull request allows the boss of the project to look through the changes and make comments before deciding to merge in the change.
$ git merge [branch_name]
Back on the master branch, merge the changes of the other branch into the master branch. Note: you have to $ git checkout master first.
$ git branch -d [branch_name]
Delete a branch after a merge. The -d flag won’t let you delete something that has not been merged.
$ git branch -d -f [branch_name] or $ git branch -D [branch_name]
Force delete a branch even if it was not merged, for example if you do not want a feature anymore.
What are the seven rules to a great commit message?
1) Seperate subject from body with a blank line. 2) Limit the subject line to 50 characters. 3) Capitalize the subject line. 4) Do not end the subject line with a period. 5) Use the imperative mood in the subject line. 6) Wrap the body at 72 characters. 7) Use the body to explain what is the problem and why you are making this change (and not how)
Redirect result into a file.
$ cmd > file (overwriting) $ cmd >> file (appending)
Redirect errors.
$ cmd 2> file (overwriting) $ cmd 2>> file (appending) $ cmd 2>&1 file (redirect both standard output and error to same file) $ cmd > file_standard 2> file_error (redirect standard output and error to different files)
Read from file or keyboard.
$ cmd < file (read from file) $ cmd << [stop word] (read from keyboard input until stop word is given)
Chain commands.
$ cmd1 | cmd2 | cmd3 (connect the output of one command to the input of another)
When should one compile a program from the source and what does it involve?
When a program is not listed in apt-get (usually not well known programs or programs in development). One should download the source, extract a compressed archive and compile manually to create an executable (equivalent of Windows .exe optimized for the user’s computer).
What is a .deb file?
Equivalent of a Windows installation program for Debian distributions (e.g. Ubuntu). A user can double-click on it and it will launch. The .deb has to correspond to the computer (32/64bits) and dependencies must already be installed.
Typical compilation process of a Linux executable.
- Install the package “build-essential” ==> compilation tool
- Find the source code of the program.
- Download and uncompress the compressed archive.
- Find the ./configure directory in the source code and execute it: $ ./configure ==> program checking all dependencies
- If there is an error, usually you have to find and install a missing dependency. Then rerun ./configure.
- Launch the compilation: $ make
- Install the executable: $ sudo make install
- To uninstall the program, run $ sudo make uninstall
How to clone an existing git repository?
$ git clone [repo_URL]
$ kill -15 [process_id] or $ kill [process_id]
Sends a SIGTERM signal to an application. The shutdown behaviour is up to the particular application:
- The process may stop imemdiately.
- The process may stop after a short delay after cleaning up resources.
- The process may keep running indefinitely.
$ kill -9 [process_id]
Sends a SIGKILL signal to init. At that point, init will stop the process. The process never gets the opportunity to catch the signal and act on it.
Is a SIGKILL signal always enough to kill a process?
- No, the kernel may not be able to successfully kill the process if the process is waiting for network or disk I/O.
- Zombie processes and processes caught in an uninterruptible sleep cannot be stopped by the kernel either.
- A reboot is required to clear those processes from the system.
What is the ps command for?
The ps (process status) command is used to provide information about the currently running processes, including their process identification numbers (PIDs).
What is the difference between kill and pkill?
pkill allows you to kill a process by its name, user name, group name, terminal, UID, EUID, and GID.
$ sudo killall -9 [process]
Kill all processes: childs and parent.
$ ps -aux | less
- -a flag: List the processes of all users on the system rather than just those of the current user, with the exception of group leaders and processes not associated with a terminal.
- -u flag: provide detailed information about each process.
- -x flag: adds to thel ist processes that have no controlling terminal, such as daemons.
- | less: piped the output of the command to the less command.
What is a daemon?
Program launched during booting and which run unobtrusively in the background until they are activated by a particular event or condition.
% ps -aux | grep [process]
Limit the processes shown to those belonging to any given user by piping the output through grep, a filter used for searching text.
What is a Bash script?
A Bash script is a plain text file which contains a series of commands. These commands are a mixture of commands we would normally type ourselves on the command line. it is a convention that Bash scripts have an extension of .sh.
What is a program?
A program is a blob of binary data consisting of a series of instructions for the CPU and possibly other resources (images, etc…) organized into a package and typically stored on a hard disk.
What is a process?
A running copy / instance of a program: instructions and resources of the program are copied from hard disk into working memory (or RAM). A bit of space in RAM is also allocated to store variables and a few flags used so that the OS can manage and tack the process.
How to execute a Bash script?
$ chmod 755 myscript.sh (by default the permissions are not set)
$ ./myscript.sh
What is the Shebang (#!) on the very first line of a Bash script?
Following the Shebang is the absolute path to the interpreter (or program) used to run (or interpret) the rest of the lines. For Bash scripts it is /bin/bash.
What care should be taken with Bash scripts?
The presence or absence of a space can be the difference between th command working or not.
How to set a variable in a Bash script?
- variable = “value” ==> allows substitution (that is include variables within the setting of the value).
- variable = ‘value’ ==> treats every character literally.
- variable = $( some command… ) ==> save the output of a command as a value.
How to export a Bash variable to a child process?
export var
./script2.sh
How to ask the user for input when executing a Bash script?
Use read:
- read var1 [var2] [var3…] ==>
- If there are more items than variable names then the remaining items will be added to the last variable name.
- if there are less items than variable names then the remaining variable names will be set to blank or null.
- read -p ‘prompt_name’ var ==> allows you to specify a prompt
- read -sp ‘prompt_name’ var ==> specify a prompt and make the input silent (do not display it).
How to make a Bash script able to process data piped to it?
Read the relevant file:
- cat /dev/stdin | some processing…
Then in the command line:
- $ cat | myscript.sh
When methods for getting user input should you use?
- Favour command lines if the script is called by other scripts or processes (e.g. CRON) and so that the data is stored in the user’s command history.
- Favour reading user input during script execution for login credentials and similar data.
- if all the script is doing is processing data in a certain way then it is best to work with STDIN.
- A combination of the previous can be used.
How to control flow in Bash scripts?
- if [] then elif [] then else fi
- Case: case in ) ;; ) ;; esac
- Boolean operators: && (AND) and || (OR)
How to get a variable in a Bash script?
Use ${var}
How to do arithmetic in Bash scripts?
- let ==> make a vriable equal to an expression.
- expr ==> print out the result of the expression.
- $(( expression )) ==> return the result of an expression.
- ${#var} ==> return the length of the variable.
What are the types of loops in Bash scripts?
- While loops: while [] do done
- Until loops: until [] do done ==> execute the commands until the test becomes true.
- For loops: for var in do done
How to create a function in a Bash script?
function_name () {
}
Notes:
- The parentheses are only a decoration: never pass anything to it.
- The function definition must appear before any calls to it.
How to pass arguments to a function in a Bash script?
function