- How to add directory to system path in Linux
- Setting PATH for your current shell session
- Using export to pass the PATH environment variable to child processes
- Setting the PATH variable for every new shell session
- Как добавить каталог в PATH в Linux
- Что такое $PATH в Linux
- Добавление каталога в ваш $PATH
- Выводы
- Linux Directory Structure and Important Files Paths Explained
- Linux Directory Structure Diagram
- Exploring Important file, their location and their Usability
How to add directory to system path in Linux
In Linux, the PATH environment variable stores the names of paths that will be searched for the executable files of any commands typed in the command line. The value of the PATH environment variable is a string containing a series of pathnames, each delimited by a colon. For instance, the default PATH on a typical system might look like this:
When you type a command such as cat and press Enter , the shell searches each of these directories for an executable file named cat. The first one it finds is the one it runs.
To view the current value of your PATH environment variable, you can use the echo command. As with all variables in the shell, when referring to the value you need to put a dollar sign before the variable name:
In the above example, the current value of path return you to the command prompt.
Setting PATH for your current shell session
You can set the value of PATH as you would any other shell variable, with the form NAME=VALUE, like this:
The problem with this command is that it will completely overwrite the values you had before, which you probably don’t want. If you want to add a new value in addition to the old ones. You can accomplish this by referring to PATH in the new definition, like this:
Using the command above adds your new path to the current value of PATH. Since the pathnames are searched in order, you probably want to add your new path at the end of the variable as we’ve done here. Instead, if you typed:
Your new path would be searched before, not after, the default system paths.
Using export to pass the PATH environment variable to child processes
This type of PATH definition sets the environment variable for your current shell session, but any new programs you run might not see the new path you’ve added. That’s because your shell lets you control the environment by requiring you to manually declare what environment variables are passed on to other programs and processes. You can accomplished this with the export command. If you run:
Any processes you run until you log out use the current value of PATH.
If you prefer, you can combine these two commands into a single line, for convenience. Put a semicolon between them so that the shell knows they’re separate commands:
If any of your pathnames have spaces in them, enclose the variable definition in quotation marks, to be safe.
Setting the PATH variable for every new shell session
The methods we’ve used so far only sets the environment variable for your current shell session; when you logout or close the terminal window, your changes will be forgotten. If you want to set PATH to a certain value every time you log in or start a new shell session, add it to your bash startup script. Every time you start an interactive shell session, bash reads the following files in order (if they exist), and executes the commands inside of them:
The first file, /etc/profile, is the default startup script for every user on the system. One or more of the remaining three files are located in the home directory of every user. Any of those three can be used, but it’s important to know that they will be searched for in this order.
You can edit these files and manually change any lines containing PATH= definitions. Be careful if you do so, because these are the directories used to locate important operating system files.
If you want to add a path for your current user only, you can leave the other PATH= lines untouched. Add a line like this to the end of the file:
If you add this to the end of the .bash_profile file in your home directory, it takes effect every time your user starts a new shell session. If you add this to /etc/profile, it takes effect for every user on the system. Note that you need administrator privileges if you want to edit /etc/profile, so you can use sudo (or be logged in as root) to do so.
Источник
Как добавить каталог в PATH в Linux
Когда вы вводите команду в командной строке, вы в основном говорите оболочке запустить исполняемый файл с заданным именем. В Linux эти исполняемые программы, такие как ls , find , file и другие, обычно find в нескольких разных каталогах вашей системы. Любой файл с исполняемыми разрешениями, хранящийся в этих каталогах, может быть запущен из любого места. Наиболее распространенные каталоги, содержащие исполняемые программы, — это /bin , /sbin , /usr/sbin , /usr/local/bin и /usr/local/sbin .
Но как оболочка узнает, в каких каталогах искать исполняемые программы? Оболочка выполняет поиск по всей файловой системе?
Ответ прост. Когда вы вводите команду, оболочка просматривает все каталоги, указанные в $PATH пользователя, в поисках исполняемого файла с таким именем.
В этой статье показано, как добавить каталоги в $PATH в системах Linux.
Что такое $PATH в Linux
Переменная среды $PATH представляет собой список каталогов, разделенных двоеточиями, который сообщает оболочке, в каких каталогах следует искать исполняемые файлы.
Чтобы проверить, какие каталоги находятся в вашем $PATH , вы можете использовать команду printenv или echo :
Результат будет выглядеть примерно так:
Если у вас есть два исполняемых файла с одинаковым именем, расположенных в двух разных каталогах, оболочка запустит файл, который находится в каталоге, который идет первым в $PATH .
Добавление каталога в ваш $PATH
Бывают ситуации, когда вы можете захотеть добавить другие каталоги в $PATH . Например, некоторые программы могут быть установлены в разных местах или вы можете захотеть иметь специальный каталог для ваших личных сценариев, но иметь возможность запускать их, не указывая абсолютный путь к исполняемым файлам. Для этого вам просто нужно добавить каталог в ваш $PATH .
Допустим, у вас есть каталог bin расположенный в вашем домашнем каталоге, в котором вы храните сценарии оболочки. Чтобы добавить каталог в ваш $PATH введите:
Команда export экспортирует измененную переменную в среду дочернего процесса оболочки.
Теперь вы можете запускать свои сценарии, вводя имя исполняемого сценария без необходимости указывать полный путь к файлу.
Однако это изменение носит временный характер и действует только в текущем сеансе оболочки.
Чтобы сделать изменение постоянным, вам необходимо определить $PATH в файлах конфигурации оболочки. В большинстве дистрибутивов Linux при запуске нового сеанса переменные среды считываются из следующих файлов:
Глобальные файлы конфигурации оболочки, такие как /etc/environment и /etc/profile . Используйте этот файл, если хотите, чтобы новый каталог был добавлен всем пользователям системы $PATH .
Файлы конфигурации для конкретной оболочки пользователя. Например, если вы используете Bash, вы можете установить $PATH в файле
/.bashrc . Если вы используете Zsh, имя файла
В этом примере мы установим переменную в файле
/.bashrc . Откройте файл в текстовом редакторе и добавьте в конец следующую строку:
Сохраните файл и загрузите новый $PATH в текущий сеанс оболочки с помощью source команды:
Чтобы убедиться, что каталог был успешно добавлен, распечатайте значение вашего $PATH , набрав:
Выводы
Добавить новые каталоги к вашему пользователю или глобальной $PATH довольно просто. Это позволяет выполнять команды и сценарии, хранящиеся в нестандартных местах, без необходимости вводить полный путь к исполняемому файлу.
Те же инструкции применимы для любого дистрибутива Linux, включая Ubuntu, CentOS, RHEL, Debian и Linux Mint.
Не стесняйтесь оставлять комментарии, если у вас есть вопросы.
Источник
Linux Directory Structure and Important Files Paths Explained
For any person, who does not have a sound knowledge of Linux Operating System and Linux File System, dealing with the files and their location, their use may be horrible, and a newbie may really mess up.
This article is aimed to provide the information about Linux File System, some of the important files, their usability and location.
Linux Directory Structure Diagram
A standard Linux distribution follows the directory structure as provided below with Diagram and explanation.
Linux Directory Structure
Each of the above directory (which is a file, at the first place) contains important information, required for booting to device drivers, configuration files, etc. Describing briefly the purpose of each directory, we are starting hierarchically.
- /bin : All the executable binary programs (file) required during booting, repairing, files required to run into single-user-mode, and other important, basic commands viz., cat, du, df, tar, rpm, wc,history, etc.
- /boot : Holds important files during boot-up process, including Linux Kernel.
- /dev : Contains device files for all the hardware devices on the machine e.g., cdrom, cpu, etc
- /etc : Contains Application’s configuration files, startup, shutdown, start, stop script for every individual program.
- /home : Home directory of the users. Every time a new user is created, a directory in the name of user is created within home directory which contains other directories like Desktop, Downloads, Documents, etc.
- /lib : The Lib directory contains kernel modules and shared library images required to boot the system and run commands in root file system.
- /lost+found : This Directory is installed during installation of Linux, useful for recovering files which may be broken due to unexpected shut-down.
- /media : Temporary mount directory is created for removable devices viz., media/cdrom.
- /mnt : Temporary mount directory for mounting file system.
- /opt : Optional is abbreviated as opt. Contains third party application software. Viz., Java, etc.
- /proc : A virtual and pseudo file-system which contains information about running process with a particular Process-id aka pid.
- /root : This is the home directory of root user and should never be confused with ‘/‘
- /run : This directory is the only clean solution for early-runtime-dir problem.
- /sbin : Contains binary executable programs, required by System Administrator, for Maintenance. Viz., iptables, fdisk, ifconfig, swapon, reboot, etc.
- /srv : Service is abbreviated as ‘srv‘. This directory contains server specific and service related files.
- /sys : Modern Linux distributions include a /sys directory as a virtual filesystem, which stores and allows modification of the devices connected to the system.
- /tmp :System’s Temporary Directory, Accessible by users and root. Stores temporary files for user and system, till next boot.
- /usr : Contains executable binaries, documentation, source code, libraries for second level program.
- /var : Stands for variable. The contents of this file is expected to grow. This directory contains log, lock, spool, mail and temp files.
Exploring Important file, their location and their Usability
Linux is a complex system which requires a more complex and efficient way to start, stop, maintain and reboot a system unlike Windows. There is a well defined configuration files, binaries, man pages, info files, etc. for every process in Linux.
- /boot/vmlinuz : The Linux Kernel file.
- /dev/hda : Device file for the first IDE HDD (Hard Disk Drive)
- /dev/hdc : Device file for the IDE Cdrom, commonly
- /dev/null : A pseudo device, that don’t exist. Sometime garbage output is redirected to /dev/null, so that it gets lost, forever.
- /etc/bashrc : Contains system defaults and aliases used by bash shell.
- /etc/crontab : A shell script to run specified commands on a predefined time Interval.
- /etc/exports : Information of the file system available on network.
- /etc/fstab : Information of Disk Drive and their mount point.
- /etc/group : Information of Security Group.
- /etc/grub.conf : grub bootloader configuration file.
- /etc/init.d : Service startup Script.
- /etc/lilo.conf : lilo bootloader configuration file.
- /etc/hosts : Information of Ip addresses and corresponding host names.
- /etc/hosts.allow : List of hosts allowed to access services on the local machine.
- /etc/host.deny : List of hosts denied to access services on the local machine.
- /etc/inittab : INIT process and their interaction at various run level.
- /etc/issue : Allows to edit the pre-login message.
- /etc/modules.conf : Configuration files for system modules.
- /etc/motd : motd stands for Message Of The Day, The Message users gets upon login.
- /etc/mtab : Currently mounted blocks information.
- /etc/passwd : Contains password of system users in a shadow file, a security implementation.
- /etc/printcap : Printer Information
- /etc/profile : Bash shell defaults
- /etc/profile.d : Application script, executed after login.
- /etc/rc.d : Information about run level specific script.
- /etc/rc.d/init.d : Run Level Initialisation Script.
- /etc/resolv.conf : Domain Name Servers (DNS) being used by System.
- /etc/securetty : Terminal List, where root login is possible.
- /etc/skel : Script that populates new user home directory.
- /etc/termcap : An ASCII file that defines the behaviour of Terminal, console and printers.
- /etc/X11 : Configuration files of X-window System.
- /usr/bin : Normal user executable commands.
- /usr/bin/X11 : Binaries of X windows System.
- /usr/include : Contains include files used by ‘c‘ program.
- /usr/share : Shared directories of man files, info files, etc.
- /usr/lib : Library files which are required during program compilation.
- /usr/sbin : Commands for Super User, for System Administration.
- /proc/cpuinfo : CPU Information
- /proc/filesystems : File-system Information being used currently.
- /proc/interrupts : Information about the current interrupts being utilised currently.
- /proc/ioports : Contains all the Input/Output addresses used by devices on the server.
- /proc/meminfo : Memory Usages Information.
- /proc/modules : Currently using kernel module.
- /proc/mount : Mounted File-system Information.
- /proc/stat : Detailed Statistics of the current System.
- /proc/swaps : Swap File Information.
- /version : Linux Version Information.
- /var/log/lastlog : log of last boot process.
- /var/log/messages : log of messages produced by syslog daemon at boot.
- /var/log/wtmp : list login time and duration of each user on the system currently.
That’s all for now. Keep connected to Tecmint for any News and post related to Linux and Foss world. Stay healthy and Don’t forget to give your value-able comments in comment section.
Источник