WeSeong Log in
← Back to posts
Linux

Linux file structure and various commands

Linux file structure and various commands

I. Overview

Linux file structureThe topmost directory is the root directory, and below that are bin, boot, dev, home, lib, media, mnt, opt, sbin, tmp, usr, var, proc, run There are directories and other file structures. The system examines which files are contained within each directory. It also identifies which files or directories are needed for a specific task. In Linux, there are... Various commandsHowever, today we will focus on commands related to user groups, file and directory commands, link commands, administrator commands, and network and system configuration commands. Additionally, we will explore how to easily edit documents in Linux. Version 6 editorLet's explore this topic.



II. Linux File Structure

While the file structure in different Linux distributions may vary, they generally share a similar structure. Understanding the file structure allows for easier and more efficient management, whether it's setting up a server or implementing security measures, using commands.Without understanding the structure, it would be difficult to know how to proceed. Initially, even when learning basic Linux commands, I didn't have a clear sense of how to use them. However, as I began to understand the file structure, I gradually started to grasp the concepts.


By default, it is placed at the top. root directoryIt is similar to "C:\Local Disk" in Windows, and because it is located at the very top of the entire directory structure, all paths in Linux start from the root directory. When you log in with an administrator account, you have access to this directory and can use it to construct paths.


  1. trash can

This directory contains executable files for Linux. It includes a collection of binary files, as well as system executable files and files related to common system commands.


  1. boot

This directory contains files related to the kernel, including the information that the kernel reads during the boot process.


  1. development

This directory contains files related to drivers. When using a virtual machine, it includes information for device control within the virtual hardware, as well as driver-related files.


  1. etc.

This directory is likely to be frequently accessed when setting up and managing a server, as it contains all the configuration files related to Linux. When installing a server (e.g., nginx), you can also access and modify the relevant configuration files in this directory.


  1. home

This directory can be thought of as similar to the user account directory in Windows. When creating a user account in Linux, a directory with the user's name is created under this directory. Generally, you can upload multiple files to this directory and then send or modify them using other paths. When logging in as a regular user, this is where the process begins.


  1. library

In Linux, a "so" file is a collection of shared object files, similar to DLL files in Windows. These files allow multiple programs to share the same code, enabling efficient management of memory (resources) when multiple processes are running. Just as Windows allows users to access the same print function from anywhere, Linux also utilizes this directory to access common program functions.


  1. media, maintenance

To understand this directory, you need to understand the concept of "mount." Mounting refers to connecting a directory to a device like a USB drive or hard drive. Think of it like connecting an external hard drive or USB drive to your Windows computer to back up or retrieve files. This allows you to utilize physical devices as directories.


※ In Ubuntu, there is a directory specifically for automatically mounting CD-ROMs. The difference between this directory and the "media" directory is the type of device it handles; for CD-ROMs, CD/DVDWhile I can read and understand the text, in the case of media, manual mounting is required. USB, external hard drives, SD cards, etc.I am reading it.


  1. option

In Windows, user programs are installed in the "Program Files" directory. In Linux, any additional user programs installed will also be placed in this directory. This is typically the directory where programs installed using commands like "sudo apt-get install program" are installed.


  1. user

This directory is similar to the "opt" directory, but it contains files related to the default applications used by regular user accounts, rather than external user programs. It includes system-related files associated with regular users.


  1. var

Logs and data files are stored here. Web servers, databases, and other source files are installed here, and many files that users directly modify are also located here. This directory is frequently accessed when setting up, managing, and operating a server.


  1. procedure

You can view process information in the Task Manager, which can be accessed using the Ctrl + Alt + Del key combination in Windows. This allows you to see details such as how much memory each running program is using and how much CPU it is consuming, from foreground programs to background processes. Similarly, this directory is where you can find process-related information in Linux.


12. run

This is the location where information such as sockets and process IDs, used for communication between servers, and files related to running services are stored.


13. sbin

This directory contains files related to system commands. If the `/bin` directory typically holds common system commands, this directory contains essential system binaries that are only accessible to users with root privileges, such as 'sudo apt update', 'sudo su', and 'sudo apt-get install program'.


14. temporary

This is a temporary file directory, and files may be moved to it when the system is shut down and restarted. It serves as a temporary holding place for files that are no longer needed, such as those in the buffer or those that have been temporarily downloaded. Before moving these downloaded files to a directory where they will be used, they are temporarily stored here.


※ As provided by VMware Copy a virtual machineThere is a way to do it.


On the screen shown above, simply move the mouse cursor over the virtual machine you want to copy, click the right mouse button, and then select "Manage" -> "Clone".


This screen appears.


On the next screen, if there is an existing snapshot, you can copy the data based on that snapshot. If there is no existing snapshot, the current state of the virtual machine will be copied.


Here, you can choose to either copy the entire data of the virtual machine as is, or link to the original virtual machine. If you're concerned about deployment, linking to the original machine can save disk space. A full clone involves copying the entire data, which requires more disk space.


Finally, you can specify the name and directory path for the virtual machine, and the process is complete.



Ⅲ. Linux Commands

Here's a summary of additional commands I've learned since my previous post.


  1. Commands related to users and groups

Regarding files related to users and groups /etc/passwd The file is important. It can be used to restrict logins by granting permissions to it when accessing and logging into Linux. All user accounts are associated with this file.


As shown in the image, the /etc/passwd file is structured like this, with each line containing the following information: ':( Colon)'The first is the user account name, which is categorized as follows: The next "x" symbol represents Encrypted passwordThis means that the first number in the following list is User IDFirst, it refers to the user's affiliation with a particular group or organization. Second, it refers to the user's involvement in a specific activity or project. Group IDThis means [insert the Korean word/phrase here]. Next, Additional informationAnd then, the next route is Home DirectoryThis refers to the default directory that is accessed immediately upon logging in with a user account. This is the path that is displayed last. ShellFor example, if the file ends with "/bin/bash", it will execute the shell when logged in as the root account.


※ Previously, it was possible to view user account passwords in the /etc/passwd file. However, this file is accessible to all users, and for security reasons, /etc/shadow The file contains a password that is encrypted in a one-way manner.


※ If `/bin/bash` is the default shell to be executed upon login, /usr/sbin/nologinEven if the password is correct, the login may be restricted. Similarly, /bin/falseWhile the system prevents logins, it incorrectly identifies even valid passwords as invalid, thus blocking access.




This is a Linux shell, and looking at the two images above, the last one is... '$'Does it end with "로"? '#'This indicates whether the user is a regular user or a super user (administrator). The '$' symbol represents a regular user, while the '#' symbol represents a super user (administrator). Typically "sudo ~"Administrative commands that begin with "sudo" can only be used when the user has superuser privileges.


This section introduces a range of commands related to users and groups, which can be widely used.

#유저추가
adduser 유저명

#유저 비밀번호 지정 및 변경
passwd 유저명

#유저 속성 변경
usermod [옵션: -c, -d, -g, -l, -s] 바꿀 내용 유저명
-- c옵션은 사용자에 대한 주석이다.
-- d옵션은 사용자의 홈디렉토리 경로를 변경한다.
-- g옵션은 사용자가 속할 그룹을 변경한다.
-- l옵션은 사용자 이름을 변경한다.
-- s옵션은 사용자의 로그인 셸을 변경한다.

#유저 삭제
userdel 유저명

#유저 암호 주기적 변경 설정
chage -m 숫자 유저명
-- m옵션 뒤의 숫자는 (몇월)을 이야기 한다.(만약, 2라면 2달 간격이다.)

#그룹 목록
groups
-- 현재 사용자가 속한 그룹을 보여준다.

#그룹 생성
groupadd 그룹명

#그룹 삭제
groupdel 그룹명

#그룹 암호 설정 혹은 관리 수행
gpasswd 그룹명

While not explicitly mentioned in the example commands, using commands related to users and groups generally requires administrator privileges.


※ When installing Linux, the initial account created is the "superuser" account, but when logging in, it functions as a regular user account. 'sudo su'This allows you to change the account to a superuser account. Once you do this, you can run commands that require administrator privileges without using `sudo`.


2. Commands related to file permissions


In the photo above, in the very front '-' and 'd' represent files and directories, respectively.This represents [the value]. Following this is a 6-digit number. r, w, x, - The combination of these four characters and symbols is significant, as it represents file or directory access permissions. There are nine characters in total, with three grouped together. Account permissions, group permissions, and other user permissions.It is. 'r' represents read permission, 'w' represents write permission, and 'x' represents execute permission.That's it. The following content is shown in the image below.


The "man" commandHowever, if you type the command you want to learn about after the "man" command, you can access helpful information about its options and explanations.



If these permissions are represented numerically, they can be expressed in octal format, as follows: If you want to grant read and write permissions, use the number 6; if you only want to grant read permissions, use the number 4; if you want to grant all permissions, use the number 7; if you only want to grant execute permissions, use the number 1; and if you want to grant no permissions, use the number 0. These numbers can be specified through commands.This can be done using either numbers or letters. For example, "r+" would grant the owner write access.

#파일 허가권 변경
chmod 숫자(ex. 777) 파일명, 디렉토리명

#파일 소유권 변경
chown 변경하려는 소유자, 그룹 변경하려는 파일, 디렉토리
chgrp 변경하려는 그룹 변경하려는 파일, 디렉토리

Both commands can change all permissions, including those in subdirectories, using the '-R' option.


3. Commands related to links

There are two types of links within the file. Hard LinkWow Symbolic Link (or Soft Link)However, hard links share data by creating a file that is a copy of the original, but the data remains even if the original file is deleted, and it can also be accessed separately. Furthermore, they share the same inode.


What is an inode? This section describes the metadata of a file, including its inode number, file mode, number of links, owner ID, file size, and location. For hard links, the same inode number is used, while symbolic links have a different inode number from the original file.


Therefore, a symbolic link creates a new inode number and links it to the original file. In effect, it's a separate file from the original, so even if the original is deleted, the link remains, but attempting to access it will result in an error because the original is no longer available. Thinking about shortcuts that are installed alongside a program on Windows might help with understanding this concept.

ln 원본 경로/파일 대상 경로/파일명
ln -s 원본 경로/파일 대상 경로/파일명

The section above explains how to create hard links, and the section below explains how to create symbolic links.


4. Commands related to packaging

While the `dpkg` command was previously used in Linux to install external programs, it was often inconvenient due to dependency issues. `apt` commandPython is a commonly used language. For example, when installing Python, the `apt` command automatically installs all the necessary packages. However, with `dpkg`, each program must be installed individually using separate commands. /etc/apt/sources.list If you view the file, you'll see a basic repository. url The path includes the necessary configuration, and using the `apt` command allows you to install related packages from this repository. Additionally, there is a private repository where you can install third-party programs, located at the path: sources.list In the file url You can install it by adding the path.

sudo apt-get install 프로그램명

#패키지 목록 업데이트
sudo apt-get update

sudo apt remove 패키지명

#사용하지 않는 패키지 제거
sudo autoremove 패키지명

#내려 받은 파일 제거
sudo apt clean/apt autoclean

#패키지 정보 보기
sudo apt-cache show 패키지명

#패키지 의존성 확인
sudo apt-cache depends 패키지명

5. Commands related to file compression

When compressing files on Windows, many people think of ZIP. Linux also allows for file compression, and in Linux, you can... tarYou will likely encounter this more often. Essentially, it's a way to bundle files together. Once files are bundled in this way xz, bz2, gz, zip, ZFurther compression may be necessary to achieve the desired format.

#파일 묶는 명령어(파일을 묶거나 풀어준다)
#묶기
tar cvf my.tar 경로

#풀기
tar xvf my.tar

#cvf와 xvf는 옵션
#옵션의 종류로
#동작 관련 옵션은 c - 묶기, x - 풀기, t - 경로 확인
#나머지 옵션으로 f - 파일, v - 묶거나 푸는 과정 보이기, J - tar + xz, z - tar + gzip, j - tar + bzip2

#이렇게 묶은 파일을 압축하고 풀 수 있다.
xz 파일명
xz -d 파일명.xz
bzip2 파일명
bzip2 -d 파일명.bz2
gzip 파일명
gzip -d 파일명.gz
zip 새로운 파일명.zip 압축할 파일 이름
unzip 압축 파일 이름.zip

#파일을 묶으면서 동시에 바로 압축까지 할 수 있다.
#gzip 형태
tar cvzf 파일명.gz 경로
tar xvzf 파일명.gz

#xz 형태
tar cvfJ 파일명.xz 경로
tar xvfJ 파일명.xz

※ When compressing files, please use the following naming convention: File extensions such as .gz, .xz, .zipThe reason for adding the extension is to avoid confusion about the type of compressed file. Since Linux does not have an extension concept, users must use the `file` command to determine the type of file.


6. Commands for finding files

The "find" command is used to discoverIt is available. Optionally -name (file name), -user (owner), -perm (permissions) It has a back -print, -execAfter finding a file, you can execute additional commands. If you don't specify an action for `-exec`, the default action is `-print` (which means to display the file's name).

find 경로 옵션 파일명/소유자/허가권 -print(디폴트), -exec 추가 명령어

which command: It provides the path to the executable file for the command. The "whereis" commandIt provides information about the location of the executable file, source code, and manual pages for a given command. Find files/keywords: Provides fast searching of filenames/keywords within the file list database.


grep 키워드 -r 경로
grep 키워드 경로

There are commands that can be used to search for content within a file. "Using 'grep' with a keyword"When used with the option '-r', it searches not only the specified file but also all files and subdirectories within.


7. Network-related commands

Modifying the configuration file for the network requires: /etc/netplan/01-network-manager-all.yaml These settings can be modified through a file. Since this is a configuration file and requires precise formatting, there is a command-line interface for editing network settings through the GUI. "nmtui"However, it's possible to easily modify these settings simply by selecting them, much like modifying BIOS settings.



Next, SSH commandWow SCP commandThis allows you to remotely access another virtual machine from a virtual machine that you have already connected to using a client like PuTTY. SCP (Secure Copy) allows you to copy files to or from a remote server. One of the options for the ssh command is '-p', which allows you to specify the port number of the remote server you want to connect to. Because the port number should only be changed for applications that are being served, you need to ensure that it matches when connecting.

ssh 계정명@IP주소(원격으로 접속하고자 하는 서버)
#그 후 해당 서버의 계정 비밀번호로 로그인해야 한다.
#원격 서버에서 내 로컬 서버로 복사(다운로드)
scp 원격서버계정@IP주소:경로 ./내서버경로

#내 로컬 서버에서 원격 서버로 업로드
scp ./내서버경로 원격서버계정@IP주소:경로

※ There is a program that allows you to directly send files from Windows to a virtual machine running Linux. The address is provided below.

Introduction to WinSCP :: WinSCP

'wget [URL address]' It is also possible to directly download files from Linux using the URL provided in the command.


※ Ubuntu allows for both server installation and operation simultaneously, while Red Hat-based systems require separate installation and operation. * sudo apt-get install nginx


8. System-related commands

Additionally, while there are more complex commands that require further study, I will provide a brief introduction to these as well. cronEgg atCron allows for the automated execution of tasks that repeat on a regular schedule, making it useful in conjunction with shell scripts. At is used to schedule and execute one-time tasks. Cron is similar to the Windows Task Scheduler, which system administrators frequently use. It is particularly useful for managing backup tasks.


For example, when dealing with cron commands. "Minute, hour, day, weekday, user command"It is used as a form. The "at" command is "at [time]" > Script > Ctrl+DIt can be used in a script format, and after the script is executed at the specified time, press Ctrl+D to complete it.


psWow topThere is a command called "ps," which displays process information. '-ef' It can also be used with options, such as '-ef'. The '-ef' option is related to the currently running process. UID (User ID), PID (Process ID), C (CPU Utilization), STIME (Start Time), TTY (Terminal Type) It displays information about the process, including the user ID (UID) that initiated the process, the process ID (PID), and the average CPU usage in minutes (C). STIME indicates the time or date when the process started, and TTY indicates the type of terminal the process is running on. '?' represents a background process, while 'pts/0' indicates a remote connection, and 'tty1' indicates a local console. The `top` command functions similarly to Windows' Task Manager, providing system resource information. Options '-n'This allows you to specify how often the screen should be refreshed, for example, every few seconds.


The `dmesg` commandYou can view the messages that appear when the system boots up, which can help identify processes or system issues that failed to run properly due to boot errors.


※ Command instructions Keywords to be executed sequentiallyThere is a semicolon at the end of each command, which allows you to chain them together. "Command; Command; Command;" This allows for the sequential execution of commands. ';' indicates the end of a command.These commands are used to differentiate between them. The `echo` command displays a string on the terminal, while the `sleep` command pauses execution for a specified time.

echo "abc"; sleep 1; echo "1234"; sleep 1; echo "finish";


Ⅳ. Linux Editors

The most commonly used tools for modifying files in Linux are: Version 6 editorIt is. Due to the nature of Linux, where all input is done through the keyboard, While an editor is essential, modifying Notepad on Windows to upload to Linux or downloading from the web can be cumbersome. Therefore, it's beneficial to be proficient in using an editor. However, initially, it may be challenging due to unfamiliarity with the editor (especially if you're used to a GUI environment like Windows), but I recommend practicing. "Command mode", "Input mode", "Line Command Mode"It is located there.

vi /etc/passwd(경로와 파일명)

Once you enter "vi" and provide the path and filename, the editor will launch. Upon entering, it defaults to command mode, but you can switch to line mode or command mode. To enter line mode, ':( Colon)'I need to enter something, and once I do, (Save), (End) You can choose to either end the editing process (w) or close the editor (q). If you add an exclamation mark (!) to "w" or "q", it will bypass the warning and immediately execute the command. Switching from command mode to input mode is done from the current cursor position. "I"By pressing or "a"Simply press the button. To return from input mode to command mode, press the button again. "ESC"Simply click on it. For basic functions, please refer to the table below.




Review

While there's a lot of new information to learn as I go, I'm finding it helpful to finally understand the network and server-related aspects that I didn't fully grasp during previous web project deployments. I'm also curious about how this will connect to cloud technology, and I'm eager to try out new Linux commands. 😁