Goglides Dev 🌱

Cover image for Linux for DevOps
Roshan Thapa
Roshan Thapa

Posted on • Originally published at github.com

Linux for DevOps

1. Introduction to Linux

What is Linux?
Linux is an open-source operating system kernel initially developed by Linus Torvalds in 1991. It is based on Unix, which is a multi-user, multitasking operating system. Linux is known for its stability, security, and flexibility.

History of Linux
Linux originated as a hobby project by Linus Torvalds in 1991. It quickly gained popularity due to its open-source nature, allowing developers worldwide to contribute to its development. Over the years, Linux has evolved into various distributions, each tailored for different purposes and user preferences.

Distributions (Distros):
Distributions are different versions of Linux packaged with specific software and configurations. Popular choices include:

  • Ubuntu: User-friendly, great for beginners.
  • Fedora: Cutting-edge technology, good for developers.
  • Debian: Stable, often the base for other distros.
  • CentOS: Enterprise-focused, known for reliability. # 2. Getting Started

Basic Concepts

File System Hierarchy :

Linux follows a hierarchical file system structure, with directories like /, /home, /etc, etc., serving different purposes.
The Linux file system hierarchy, also known as the Filesystem Hierarchy Standard (FHS), defines a standardized layout for organizing files and directories on Linux systems. This structure ensures consistency across different distributions and simplifies system administration. Here's a breakdown of some key directories within the FHS:

Root Directory (/)

  • The root directory is the starting point of the entire file system hierarchy. All other directories branch out from here.

Essential Directories:

  • /bin: Contains essential command-line binaries that are needed even in single-user mode. Examples: ls (list directory contents), cp (copy files), mv (move files).
  • /boot: Stores static files required for booting the system, including the kernel and initial RAM disk.
  • /dev: Device files provide access to hardware devices like hard drives, network interfaces, etc.
  • /etc: Holds system-wide configuration files, such as network settings, user accounts, and application configurations.
  • /home: Houses user home directories, containing personal files, documents, and application data. Each user has a separate directory under /home.
  • /lib: Stores essential libraries needed by programs in /bin and /sbin.
  • /lib64: Similar to /lib, but contains 64-bit libraries for 64-bit systems.
  • /sbin: Holds essential system administration binaries that may not be needed by regular users. Examples: fdisk (partition disks), mount (mount filesystems).
  • /usr: The largest directory in the FHS, containing most user applications, libraries, and documentation.
    • /usr/bin: Contains a broader range of executable programs for everyday use.
    • /usr/sbin: Similar to /sbin, but contains system administration programs typically used by root or privileged users.
    • /usr/lib & **/usr/lib64: Additional system libraries needed by applications in /usr/bin and /usr/sbin.
    • /usr/share: Stores shared data like documentation, icons, and fonts used by applications.
  • /var: Contains variable data that changes over time, such as logs, temporary files, and spool directories.
    • /var/log: Stores system logs for various services and applications.
    • /var/tmp: Used for temporary files that can be safely deleted after use.

Other Directories (depending on the system):

  • /mnt: A mount point for temporarily mounting external filesystems.
  • /opt: Intended for storing add-on software packages that are not part of the base distribution.
  • /proc: A pseudo-filesystem that provides information about processes, memory, and other system aspects.
  • /run: Stores temporary files and information needed by the system during its current run.
  • /sys: Another pseudo-filesystem providing information about the system hardware and kernel configuration.

Understanding the FHS structure is crucial for navigating the Linux file system effectively. Remember, this is a general guideline, and some variations might exist depending on the specific Linux distribution. Consult your distribution's documentation for any deviations from the standard.

Users, Groups, and Permissions :

In Linux, a robust security system relies on a well-defined structure for users, groups, and permissions. This ensures controlled access to files and resources, protecting the system's integrity and user privacy.

1. Users:

  • Each user on a Linux system has a unique identifier (UID) and an associated username.
  • Users can log in to the system using their username and password.
  • User accounts can be created, modified, or deleted using commands like useradd, usermod, and userdel (requires root privileges). User Management: useradd <username> - Create a new user. passwd <username> - Set password for a user. usermod <username> - Modify user attributes. userdel <username> - Delete a user (use with caution).

2. Groups:

  • Groups allow for managing access privileges for multiple users efficiently.
  • Users can belong to one or more groups.
  • A group also has a unique identifier (GID) and a group name.
  • Groups are created and managed using commands like groupadd, groupmod, and groupdel (requires root privileges). Group Management: groupadd <groupname> - Create a new group. groupmod <groupname> - Modify group attributes. groupdel <groupname> - Delete a group (use with caution).

3. Permissions:

  • Permissions define what a user or group can do with a file or directory:
    • Read (r): Allows viewing the content of a file or listing the contents of a directory.
    • Write (w): Allows modifying the content of a file or creating/deleting files within a directory.
    • Execute (x): Allows running a file if it's an executable program or script.
  • Permissions are assigned to three categories:
    • User (u): The owner of the file or directory.
    • Group (g): The group the file or directory belongs to.
    • Others (o): All other users on the system. Permission Management: ls -l - List detailed information about files, including permissions. chmod - Change file permissions. (complex, see details below) chown - Change file ownership.

4. Viewing Permissions:

  • The ls -l command displays detailed file information, including permissions.
  • Permissions are represented by a three-character string:
    • The first character indicates the file type (e.g., - for regular file, d for directory).
    • The next three characters represent permissions for user, group, and others, each consisting of r, w, or - (dash for no permission).

5. Changing Permissions:

  • The chmod command allows modifying file permissions.
  • The syntax is: chmod <permission> <file/directory>
  • Permissions can be specified symbolically (e.g., u+rwx, grant read, write, and execute to the user) or numerically (e.g., chmod 777 filename, grant full permissions to all).

6. Ownership:

  • Each file and directory has an owner (user) and a group assigned to it.
  • The chown command allows changing the ownership of a file or directory (requires root privileges). #### Examples:

Change Ownership of a File:

`chown user1 file.txt` 
Enter fullscreen mode Exit fullscreen mode

This command changes the ownership of file.txt to user1, keeping the group ownership unchanged.

Change Ownership of a Directory Recursively:

`chown -R user1:group1 directory/` 
Enter fullscreen mode Exit fullscreen mode

This command recursively changes the ownership of directory/ and all its contents to user1 and group1.

Change Group Ownership Only:

`chown :group2 file.txt` 
Enter fullscreen mode Exit fullscreen mode

This command changes only the group ownership of file.txt to group2, keeping the user ownership unchanged.

Change Ownership by UID and GID:

`chown 1001:1002 file.txt` 
Enter fullscreen mode Exit fullscreen mode

This command changes the ownership of file.txt to the user with UID 1001 and the group with GID 1002.

Common Options:

  • -R, --recursive: Change ownership recursively for directories and their contents.
  • -v, --verbose: Display a message for each file processed.
  • --dereference: Dereference symbolic links when changing ownership of linked files.

Notes:

  • To view ownership information for files and directories, you can use the ls -l command.
  • Only the root user (superuser) or a user with appropriate permissions can change ownership of files and directories.

7. Real-world Example:

Imagine a document named "confidential.txt" that needs to be accessible only to the user "manager" and the group "finance."

  • We can create a group "finance" using groupadd finance.
  • Add the "manager" user to the "finance" group using usermod -a -G finance manager.
  • Set permissions on "confidential.txt" using chmod 640 confidential.txt. This grants read (r) permission to the owner ("manager") and the group ("finance"), and no permission to others.

Understanding users, groups, and permissions is essential for effective file system management and system security in Linux.

Command Line Interface (CLI):

The Command Line Interface (CLI), also known as the terminal or shell, is the heart and soul of Linux. It provides a text-based environment where you interact with the system by typing commands. Here's a breakdown of the key concepts and basic commands to get you started:

1. The Shell

  • The shell acts as an interpreter between you and the operating system kernel.
  • Common shells in Linux include Bash (Bourne Again SHell) and Zsh.
  • The shell displays a prompt (usually $ or #) where you type commands.

2. Basic Navigation

  • Use the pwd command to see your current working directory.
  • Change directories with cd:
    • cd ..: Move up one directory level.
    • cd ~: Go to your home directory.
    • cd /path/to/directory: Change to a specific directory.

3. Listing Files and Directories

  • Use ls to list files and directories in the current directory.
  • ls -l: Provides a detailed listing with permissions, owner, group, size, and last modification time.
  • ls -a: Shows hidden files (starting with a dot .) as well.

4. Working with Files

  • Create a new file: touch filename.txt
  • View the contents of a file: cat filename.txt
  • Edit a file: nano filename.txt (or other text editors like vim)
  • Copy a file: cp source_file destination_file
  • Move a file: mv source_file destination_file (or rename within the same directory)

- Delete a file: rm filename.txt (use with caution!)

Common Options:

  • -l: Long listing format. Provides detailed information about files, including permissions, owner, group, size, and last modification time.
  • -a: List all files, including hidden files starting with a dot (.). By default, hidden files are hidden.
  • -h: Human-readable format for file sizes. Displays sizes in KB, MB, GB, etc., instead of bytes.
  • -t: Sort by modification time, with the most recently modified files appearing at the bottom (default).
  • -r: Reverse sort order (can be combined with -t for oldest first).
  • -S: Sort by size, largest first.

5. Helpful Commands

  • man <command>: Displays the manual page for a specific command, providing detailed information and usage examples.
  • history: Shows a list of previously executed commands.
  • clear: Clears the terminal screen.
  • exit: Exits the terminal session.

6. Getting Help

  • If you're stuck or unsure about a command, use man <command> for the manual page.
  • Many online resources offer tutorials and explanations for Linux commands.

Remember: The CLI offers a vast array of commands beyond these basics. As you explore further, you'll discover commands for managing users, permissions, processes, networking, and much more. Experiment in a safe environment (like a virtual machine) to practice and gain confidence using the Linux CLI.

7. linux for DevOps

who

Shows all users connected

[root@localhost ~]# who
root     tty1         2024-03-10 10:41
root     pts/0        2024-03-10 10:41 (192.168.56.1)
Enter fullscreen mode Exit fullscreen mode

whoami

Tells which user is currently logged in.

[root@localhost ~]# whoami
root
Enter fullscreen mode Exit fullscreen mode

who am i

[root@localhost ~]# who am i
root     pts/0        2024-03-10 10:41 (192.168.56.1)
Enter fullscreen mode Exit fullscreen mode

sudo su

Switches to the root user.
[root@localhost ~]# sudo su

pwd

[root@localhost ~]# pwd
/root
Enter fullscreen mode Exit fullscreen mode

ls

Lists files and folders in the current directory.

[root@localhost ~]# ls
anaconda-ks.cfg  a.txt  b.txt  c.txt
Enter fullscreen mode Exit fullscreen mode

ls -ltr

Lists files with timestamps in reverse order.

[root@localhost ~]# ls -ltr

    total 4
    -rw-------. 1 root root 1321 Dec  7 16:28 anaconda-ks.cfg
    -rw-r--r--  1 root root    0 Mar 10 10:49 c.txt
    -rw-r--r--  1 root root    0 Mar 10 10:49 b.txt
    -rw-r--r--  1 root root    0 Mar 10 10:49 a.txt
Enter fullscreen mode Exit fullscreen mode

ls -ltra

[root@localhost ~]# ls -ltra
total 32
-rw-r--r--.  1 root root  129 Dec 29  2013 .tcshrc
-rw-r--r--.  1 root root  100 Dec 29  2013 .cshrc
-rw-r--r--.  1 root root  176 Dec 29  2013 .bashrc
-rw-r--r--.  1 root root  176 Dec 29  2013 .bash_profile
-rw-r--r--.  1 root root   18 Dec 29  2013 .bash_logout
-rw-------.  1 root root 1321 Dec  7 16:28 anaconda-ks.cfg
dr-xr-xr-x. 19 root root 4096 Mar  6 11:56 ..
-rw-------.  1 root root 2237 Mar  6 12:03 .bash_history
-rw-r--r--   1 root root    0 Mar 10 10:49 c.txt
-rw-r--r--   1 root root    0 Mar 10 10:49 b.txt
-rw-r--r--   1 root root    0 Mar 10 10:49 a.txt
dr-xr-x---.  2 root root  174 Mar 10 10:49 .
Enter fullscreen mode Exit fullscreen mode

touch

Creates an empty file.

[root@localhost ~]# touch abc.txt
Enter fullscreen mode Exit fullscreen mode

touch <.filename>

Creates hidden files and folders starting with a dot.

[root@localhost ~]# touch .hidden.txt
Enter fullscreen mode Exit fullscreen mode

mkdir

Creates a directory.

[root@localhost ~]# mkdir hello_dir
Enter fullscreen mode Exit fullscreen mode

cd

Change directory

[root@localhost ~]# cd hello_dir/
Enter fullscreen mode Exit fullscreen mode

cd ..

Go one directory to lower

[root@localhost hello_dir]#  cd ..
[root@localhost ~]#
Enter fullscreen mode Exit fullscreen mode

cp

[root@localhost ~]# cp a.txt x.txt
[root@localhost ~]# ls
abc.txt  anaconda-ks.cfg  a.txt  b.txt  c.txt  hello_dir  x.txt
Enter fullscreen mode Exit fullscreen mode

mv

[root@localhost ~]# mv b.txt z.txt
[root@localhost ~]# ls
abc.txt  anaconda-ks.cfg  a.txt  c.txt  hello_dir  pass.txt  x.txt  z.txt
Enter fullscreen mode Exit fullscreen mode

rm -rf

[root@localhost ~]# rm -rf pass.txt
[root@localhost ~]# ls
abc.txt  anaconda-ks.cfg  a.txt  c.txt  hello_dir  x.txt  z.txt
Enter fullscreen mode Exit fullscreen mode

echo

Display in the standard output

[root@localhost ~]# echo "hello"
hello
Enter fullscreen mode Exit fullscreen mode

df -h

[root@localhost ~]# df -h
Filesystem               Size  Used Avail Use% Mounted on
devtmpfs                 1.9G     0  1.9G   0% /dev
tmpfs                    1.9G     0  1.9G   0% /dev/shm
tmpfs                    1.9G  8.7M  1.9G   1% /run
tmpfs                    1.9G     0  1.9G   0% /sys/fs/cgroup
/dev/mapper/centos-root   38G  2.0G   36G   6% /
/dev/mapper/centos-home   19G   33M   19G   1% /home
/dev/sda1               1014M  190M  825M  19% /boot
tmpfs                    379M     0  379M   0% /run/user/0
Enter fullscreen mode Exit fullscreen mode

overwrite file

[root@localhost ~]#cat /etc/passwd > pass.txt

[root@localhost ~]# cat pass.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
Enter fullscreen mode Exit fullscreen mode

append file

[root@localhost ~]#cat /etc/passwd >> pass.txt

[root@localhost ~]# cat pass.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
adm:x:3:4:adm:/var/adm:/sbin/nologin
lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
sync:x:5:0:sync:/sbin:/bin/sync
shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown
Enter fullscreen mode Exit fullscreen mode

cat

Displays the content of a file.

[root@localhost ~]# cat pass.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
Enter fullscreen mode Exit fullscreen mode

more

Displays file content one page at a time.

[root@localhost ~]# more pass.txt
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
Enter fullscreen mode Exit fullscreen mode

grep

Here are some details about the grep command:

  1. Usage: The basic usage of grep is:

    grep [options] pattern [file...]

-   `pattern` is the regular expression you want to search for.
-   `file...` specifies the files you want to search in. If no file is provided, `grep` reads from the standard input (stdin).
Enter fullscreen mode Exit fullscreen mode
  1. Options:
-   `-i`: Perform a case-insensitive search.
-   `-v`: Invert the match, i.e., display lines that do not match the pattern.
-   `-E`: Interpret the pattern as an extended regular expression (enables additional features like using `|` for alternation).
-   `-r` or `-R`: Recursively search subdirectories.
-   `-n`: Display line numbers along with matching lines.
-   `-c`: Display only the count of matching lines, rather than the lines themselves.
-   `-l`: Display only the names of files containing matching lines, rather than the lines themselves.
-   `-w`: Match whole words only.
-   `-A`, `-B`, `-C`: Display lines of context (after, before, or around) the matching lines.
-   `-x`: Match the whole line exactly.
Enter fullscreen mode Exit fullscreen mode
  1. Regular Expressions: grep uses regular expressions (regex) for pattern matching. Regular expressions allow you to specify complex search patterns. For example:
-   `.` matches any single character.
-   `*` matches zero or more occurrences of the previous character.
-   `^` matches the beginning of a line.
-   `$` matches the end of a line.
-   `[...]` matches any one of the characters inside the brackets.
-   `|` represents alternation (logical OR).
-   `\` is used to escape special characters.
Enter fullscreen mode Exit fullscreen mode
  1. Examples:
-   `grep "pattern" file.txt`: Search for lines containing "pattern" in the file `file.txt`.
-   `grep -i "pattern" file.txt`: Perform a case-insensitive search.
-   `grep -r "pattern" directory/`: Recursively search for "pattern" in all files under the `directory/`.
-   `grep -E "pattern1|pattern2" file.txt`: Search for lines containing either "pattern1" or "pattern2".
Enter fullscreen mode Exit fullscreen mode

grep is a powerful tool for searching text files and is commonly used in conjunction with other commands in shell scripting and text processing tasks.

Text Editor (vi) Commands

  • vi <filename>: Opens the file in vi editor.
  • Esc: Switches between insert and normal mode.
  • i: Enters insert mode.
  • :wq: Saves changes and exits.
  • :q!: Exits without saving.
  • Esc 3 Y: Yanks (copies) three lines.
  • Esc p: Pastes the copied text.

Permissions

  • r: Read (4)
  • w: Write (2)
  • x: Execute (1)
  • First 3: Owner
  • Second 3: Group
  • Last 3: Others

Permissions Example

  • chmod o+rwx b.txt: Gives others read, write, and execute permissions to file "b.txt".
  • chmod o-rwx b.txt : Remove others read, write, and execute permissions to file "b.txt".
  • chmod 777 b.txt : Gives all_user read, write, and execute permissions to file "b.txt".

User and Group Management

  • sudo groupadd -g 2501 stdgrp01: Adds a group with group ID 2501.
  • sudo groupdel <groupname>: Deletes a group.
  • sudo useradd -g 2501 -u 1501 nssstd01: Adds a user to a specific group with a specific user ID.
  • sudo userdel <username>: Deletes a user.

3. Package Management

In Linux, package management plays a crucial role in efficiently installing, updating, removing, and maintaining software. Imagine not having to compile software from source code every time you need a new program! Package managers take care of the complexities, ensuring smooth software management. Here's a breakdown of the most common package management systems in Linux:

1. Debian Package Management System (dpkg):

  • Found on Debian-based distributions like Ubuntu, Mint, etc.
  • The core tool for installing, removing, and querying packages.
  • Use dpkg -i package.deb to install a DEB package file.
  • However, dpkg has limitations in dependency resolution.

2. Advanced Package Tool (APT):

  • Built on top of dpkg and offers a more user-friendly interface.
  • Handles dependency resolution automatically, ensuring all necessary packages are installed for a program to function correctly.
  • Common APT commands:
    • apt update: Updates the list of available packages.
    • apt install package_name: Installs a package.
    • apt upgrade: Upgrades all installed packages to their latest versions.
    • apt remove package_name: Removes a package.

3. Yellowdog Updater, Modified (YUM):

  • Used on Red Hat-based distributions like Fedora, CentOS, etc.
  • Similar to APT in functionality but uses RPM (RPM Package Manager) as the underlying tool.
  • Common YUM commands:
    • yum update: Updates the package list.
    • yum install package_name: Installs a package.
    • yum upgrade: Upgrades all installed packages.
    • yum remove package_name: Removes a package.

4. Dandified YUM (DNF):

  • A newer version of YUM, aiming for faster performance and improved dependency management.
  • Available on Fedora and other Red Hat-based systems.
  • Commands are identical to YUM.

5. pacman:

  • The package manager for Arch Linux and its derivatives.
  • Known for its rolling release model, where updates are delivered continuously.
  • pacman offers a simple and powerful command-line interface for package management.
  • Common pacman commands:
    • pacman -Syu: Updates package lists and upgrades installed packages.
    • pacman -S package_name: Installs a package.
    • pacman -R package_name: Removes a package.

Choosing the Right Package Manager:

The choice depends on your Linux distribution. Most distributions have their preferred package manager pre-installed and configured. Using the recommended package manager for your distro is generally the best approach.

Benefits of Package Management:

  • Convenience: Easy installation, update, and removal of software.
  • Dependency Resolution: Ensures all required dependencies are met for a program to run.
  • Security: Package repositories are often maintained by the distribution, providing some level of quality control and security updates.

By understanding package management, you'll be able to effectively install, update, and maintain software on your Linux system, keeping it secure and running smoothly.

4. System Administration in Linux

System administration in Linux involves managing and maintaining a Linux system to ensure its smooth operation, security, and user access. Here's a deeper dive into the tasks you mentioned:

User and Group Management:

  • Adding Users: Use adduser (or useradd on some systems) to create new user accounts. You can specify options like the user's full name, password (use a strong password!), home directory location, and shell.
  • Modifying Users: Use usermod to modify existing user accounts. You can change properties like full name, password, group membership, and shell.
  • Deleting Users: Use deluser (or userdel) to remove user accounts. This typically deletes the user's home directory as well (unless specified otherwise).

Group Management:

  • Adding Groups: Use addgroup to create new groups.
  • Modifying Groups: Use groupmod to modify existing groups, such as changing the group name.
  • Deleting Groups: Use delgroup to remove groups. Ensure no users belong to the group before deletion.

Process Management:

  • Viewing Processes: Use ps (process status) to list running processes. You can use options to filter by user, process ID (PID), or other criteria.
  • Monitoring Processes: Use top to display a real-time view of running processes, including CPU and memory usage. You can use commands within top to kill or prioritize processes.
  • Terminating Processes: Use kill to terminate a running process. Use the process ID (PID) obtained from ps to target the specific process.

System Configuration:

  • Network Configuration: Edit network configuration files (e.g., /etc/network/interfaces) or use tools like ifconfig (older systems) or nmcli (newer systems) to configure network interfaces, IP addresses, subnet masks, and gateways.
  • Hostname: Use hostnamectl set-hostname <new_hostname> to change the system's hostname.
  • Timezone: Use timedatectl to set the system's time zone. Explore the available options to select your desired location.
  • Firewall: Use tools like iptables (traditional firewall) or firewalld (newer firewall) to configure firewall rules that control incoming and outgoing network traffic.

System Monitoring:

  • htop: A more user-friendly alternative to top, providing a real-time view of system resources like CPU, memory, disk usage, and processes.
  • sar (System Activity Reporter): Collects and reports system activity information at regular intervals. Useful for analyzing historical performance data.
  • nmon: Another monitoring tool offering detailed system performance metrics, including CPU, memory, network, disk I/O, and more.

Additional Tips:

  • Always back up configuration files before making significant changes.
  • Use the man command to access detailed documentation for each system administration tool.
  • Consider using a virtual machine to experiment with system administration tasks in a safe environment before applying them to your main system.

By mastering these core system administration functionalities, you'll be well on your way to managing and maintaining your Linux system effectively.

5. Linux Command Cheatsheet

Command Output
Bash Commands
uname -a Show system and kernel
head -n1 /etc/issue Show distri­bution
mount Show mounted filesy­stems
date Show system date
uptime Show uptime
whoami Show your username
man command Show manual for command
Bash Shortcuts
CTRL-c Stop current command
CTRL-z Sleep program
CTRL-a Go to start of line
CTRL-e Go to end of line
CTRL-u Cut from start of line
CTRL-k Cut to end of line
CTRL-r Search history
!! Repeat last command
!abc Run last command starting with abc
!abc:p Print last command starting with abc
!$ Last argument of previous command
ALT-. Last argument of previous command
!* All arguments of previous command
^abc^123 Run previous command, replacing abc with 123
Bash Variables
env Show enviro­nment variables
echo $NAME Output value of $NAME variable
export NAME=value Set $NAME to value
$PATH Executable search path
$HOME Home directory
$SHELL Current shell
IO Redire­ction
cmd < file Input of cmd from file
cmd1 <(cmd2) Output of cmd2 as file input to cmd1
cmd > file Standard output (stdout) of cmd to file
cmd > /dev/null Discard stdout of cmd
cmd >> file Append stdout to file
cmd 2> file Error output (stderr) of cmd to file
cmd 1>&2 stdout to same place as stderr
cmd 2>&1 stderr to same place as stdout
cmd &> file Every output of cmd to file
cmd refers to a command.
cmd1 cmd2
cmd1 & cmd2
Command Lists
cmd1 ; cmd2 Run cmd1 then cmd2
cmd1 && cmd2 Run cmd2 if cmd1 is successful
cmd1
cmd & Run cmd in a subshell
Directory Operations
pwd Show current directory
mkdir dir Make directory dir
cd dir Change directory to dir
cd .. Go up a directory
ls List files
ls Options
-a Show all (including hidden)
-R Recursive list
-r Reverse order
-t Sort by last modified
-S Sort by file size
-l Long listing format
-1 One file per line
-m Comma-­sep­arated output
-Q Quoted output
Search Files
grep pattern files Search for pattern in files
grep -i Case insens­itive search
grep -r Recursive search
grep -v Inverted search
grep -o Show matched part of file only
find /dir/ -name name* Find files starting with name in dir
find /dir/ -user name Find files owned by name in dir
find /dir/ -mmin num Find files modifed less than num minutes ago in dir
whereis command Find binary / source / manual for command
locate file Find file (quick search of system index)
File Operations
touch file1 Create file1
cat file1 file2 Concat­enate files and output
less file1 View and paginate file1
file file1 Get type of file1
cp file1 file2 Copy file1 to file2
mv file1 file2 Move file1 to file2
rm file1 Delete file1
head file1 Show first 10 lines of file1
tail file1 Show last 10 lines of file1
tail -F file1 Output last lines of file1 as it changes
Watch a Command
watch -n 5 'ntpq -p' Issue the 'ntpq -p' command every 5 seconds and display output
Process Management
ps Show snapshot of processes
top Show real time processes
kill pid Kill process with id pid
pkill name Kill process with name name
killall name Kill all processes with names beginning name
Nano Shortcuts
Files
Ctrl-R Read file
Ctrl-O Save file
Ctrl-X Close file
Cut and Paste
ALT-A Start marking text
CTRL-K Cut marked text or line
CTRL-U Paste text
Navigate File
ALT-/ End of file
CTRL-A Beginning of line
CTRL-E End of line
CTRL-C Show line number
CTRL-_ Go to line number
Search File
CTRL-W Find
ALT-W Find next
CTRL-\ Search and replace
Screen Shortcuts
screen Start a screen session.
screen -r Resume a screen session.
screen -list Show your current screen sessions.
CTRL-A Activate commands for screen.
CTRL-A c Create a new instance of terminal.
CTRL-A n Go to the next instance of terminal.
CTRL-A p Go to the previous instance of terminal.
CTRL-A " Show current instances of terminals.
CTRL-A A Rename the current instance.
File Permis­sions
chmod 775 file Change mode of file to 775
chmod -R 600 folder Recurs­ively chmod folder to 600
chown user:group file Change file owner to user and group to group
File Permission Numbers First digit is owner permis­sion, second is group and third is everyone.
Calculate permission digits by adding numbers below.
4 read (r)
2 write (w)
1 execute (x)

Top comments (1)

Collapse
 
bart97coder profile image
Bart97coder

I prefer windows over linux anyway