What source command in linux

What is Source Command in Linux and How Does it Work?

The source command executes commands from a file in the current shell. It can also be used to refresh environment variables and to be honest, the primary use of source command is to refresh environment variables.

You can also use . (dot) instead of source command like this:

How does source command work?

The syntax of this command is simple, but understanding it requires a slightly deeper look at some Linux concepts. If you’re brand new to Linux or programming, you might only have a vague idea about what a variable is.

If you’ve heard this term, but don’t know exactly what it means, that is okay! Remember, all of us start from exactly the same place. No one suddenly wakes up in the morning being a system administrator or programmer.

I will give a brief explanation before moving on.

You may skip to the next header if you’re already familiar with how to create variables in bash.

Overview of Variables

You can open any bash terminal and create new variables. A variable can be thought of as a placeholder that can be used to point your system to a piece of information (letters, numbers or symbols).

Let’s look at an example. I am going to make a new variable called name and I’m going to assign the value Christopher.

In bash, this is done using the formula: variable_name=your_variable. Do not add any spaces between = symbol and your text.

What happens if I just type the variable name?

If you forget this symbol, bash will return the text that you’ve entered. Here, I tell it to echo, or print, “name”. Without the $ symbol, bash does not recognize that you want to use the variable you’ve created.

Your variable will be inserted where it is called. So I can also include it in a sentence like this:

There are many things you can do with variables, but I’m hoping that primer will be enough to allow anyone reading this to understand how they work.

Environment variables vs shell Variables

For the next key to understanding source command, let’s talk about persistence. This is an easy way to think about the difference between shell and environmental content. You might also think of it in terms of “portability” depending on the context.

Simply put, if you create a variable in a terminal shell, it will be lost once you exit that shell.

In contrast, an environmental variable has persistence in your operating system. These variables typically use all caps to distinguish themselves.

An example of this is your username which is known by the OS as $USER.

Okay, so you spent quite a bit of time going over the differences between environment and shell variables. What does that have to do with source? Everything, really.

Читайте также:  Запуск планировщика задач windows

Otherwise there would be no difference in running source and bash. In order to illustrate this point, I have one more demonstration lined up.

Source vs Bash

If you’ve been around Linux for a little while, you may have encountered these commands and thought they did the same thing. After all, both commands can be used to execute a script.

Source works in the current shell, unlike running bash which creates a new shell. This isn’t obvious since no new windows are displayed.

If you’re following along, this one will require you to write a very simple script (let’s call it echo.sh) that looks like this:

Before you do anything else in your terminal, assign your name to the variable name.

Next, I am going to show you what happens when you try all 3 commands in the same terminal that you assigned your variable in.

As you can see, your local variable was not recognized when you executed your script via bash.

Refresh environment variables with source command

Source can also be used to update environmental variables in the current shell. A common application for this task is updating your bash profile in the current shell.

A user may want to modify their bash profile to, say, create an alias. Normally, once you save the configuration you will need to open a new terminal window for the changes to take place.

Running this will refresh the settings in your current shell without forcing you to open a new terminal.

Conclusion

We hope that you enjoyed this tutorial on the source command. As always, please let us know your thoughts in the comment section. If you enjoyed this post please share it on social media using the buttons below.

Источник

Команда source в Linux

Командная оболочка играет очень важную роль в работе семейства операционных систем Linux. Она используется не только пользователями для работы в терминале, но и программами, а также компонентами операционной системы для обмена данными между собой. Для этого применяются переменные окружения. Для перезагрузки переменных окружения из файла часто используется команда source.

Эта команда позволяет выполнить скрипт в текущем процессе оболочки bash. По умолчанию для выполнения каждого скрипта запускается отдельная оболочка bash, хранящая все его переменные и функции. После завершения скрипта всё это удаляется вместе с оболочкой. Команда source позволяет выполнить скрипт в текущем командном интерпретаторе, а это значит, что всё переменные и функции, добавленные в этом скрипте, будут доступны также и в оболочке после его завершения. Как вы уже поняли, в этой статье будет рассмотрена команда source linux.

Команда source linux

Синтаксис команды очень прост. Надо вызвать саму команду и передать ей путь к исполняемому файлу:

$ source путь_к_файлу аргументы

Никаких опций более не нужно. Если указан не абсолютный путь к файлу, а просто имя файла, то утилита будет искать исполняемый файл в текущей папке и директориях, указанных в переменной PATH. Давайте разберём несколько примеров работы с утилитой. Создаём скрипт, объявляющий переменную:

Затем загрузим переменную из этого файла:

Теперь можно попытаться вывести содержимое переменной и убедиться, что всё работает:

Однако, переменная есть только в текущем командном интерпретаторе, в других командных интерпретаторах её нет. Это отличие команды source от команды export, позволяющей экспортировать переменные окружения глобально.

Читайте также:  Minecraft windows 10 edition обзор

Если выполняемому скрипту нужно передать параметры, можно это сделать, просто перечислив их после пути к файлу скрипта. Модифицируем наш скрипт, чтобы переменная бралась из первого параметра:

И снова выполняем:

source losstsource losst.ru

Аналогично работают и функции. Если объявить функцию в скрипте bash, а затем выполнить его с помощью команды source linux, то функция станет доступна в интерпретаторе:

#!/bin/bash
print_site() <
echo «losst.ru»
>

Теперь можно выполнить функцию print_site в терминале или любом другом скрипте:

Для тех, кто знаком с программированием на языке Си, можно провести аналогию с директивой #include, делающей доступными в текущем файле функции из других файлов. Если файл, имя которого передано как параметр команде, не существует, она вернёт код возврата 1 и завершится:

Вместо команды source можно использовать точку (.), однако здесь следует быть осторожными — между точкой и именем файла должен быть пробел для того, чтобы bash интерпретировал эту точку как отдельную команду, а не как часть имени файла:

Однако, нельзя писать .losstsource или ./losstsource, потому что обозначение ./ — это уже отсылка на текущую директорию, скрипт будет выполнен как обычно.

Выводы

В этой небольшой статье мы рассмотрели работу с командой source linux. Как видите, это очень простая и в то же время полезная команда, очень сильно облегчающая работу в терминале. Именно с её помощью работают виртуальные окружения Python и многие другие подсистемы.

Источник

source command in Linux with Examples

source is a shell built-in command which is used to read and execute the content of a file(generally set of commands), passed as an argument in the current shell script. The command after taking the content of the specified files passes it to the TCL interpreter as a text script which then gets executed. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise, the positional parameters remain unchanged. The entries in $PATH are used to find the directory containing FILENAME, however if the file is not present in $PATH it will search the file in the current directory. The source command has no option and the argument is the file only.

Syntax:

Example 1: To pass gfg.txt as an argument which is stored in the home directory and contain list of command i.e. ls, date and time. Each command enlisted in the file will be executed line by line.

Example 2: To pass a path_name of a file as an argument where, /home/sc/sourcefolder/ is the file directory here. The content of the file is written below:

echo ” Hello, Welcome to Geeksforgeeks”
echo “current directory is:”
pwd
echo “Date is:”
date

Источник

Source command

  • The source command can be used to load any functions file into the current shell script or a command prompt.
  • It read and execute commands from given FILENAME and return.
  • The pathnames in $PATH are used to find the directory containing FILENAME. If any ARGUMENTS are supplied, they become the positional parameters when FILENAME is executed.

Contents

Syntax

Example

Create a shell script called mylib.sh as follows:

Save and close the file. You can now call and use function is_root() from mylib.sh using the following syntax in your script called test.sh:

Save and close the file. Run it as follows:

Our previous example can be updated using source command as follows:

A Note About Exit Status

This command returns the status of the last command executed in FILENAME; fails if FILENAME cannot be read. In this example, /etc/init.d/function exists and source using the following command:

Читайте также:  Планшет windows gps приемник

The exit status 0 indicate that source commanded successfully read /etc/init.d/function file. In this example, /etc/init.d/foo does not exists and source using the following command:

The exit status 1 indicate that source commanded failed to read /etc/init.d/foo file.

Working with internal command

The source command is the reliable way when you need to run internal commands in your shell script. Here is how to use the cd command in bash scripts that change the current script’s directory as per script in the current shell.

Problematic code

Try the following example:

Solution

So running a shell script executes in its independent process. In other words, you are running the above script in a subshell. To fix this and run the script in the current shell so that the cd command works and you will be in the /etc/ folder when the script finished executing:

Источник

Команда source в Bash

source команда считывает и выполняет команды из файла, указанного в качестве аргумента в текущей среде оболочки. Полезно загружать функции, переменные и файлы конфигурации в сценарии оболочки.

source — это оболочка, встроенная в Bash и другие популярные оболочки, используемые в операционных системах Linux и UNIX. Его поведение может немного отличаться от оболочки к оболочке.

Синтаксис команды source

Синтаксис source команды следующий:

  • source и . (точка) — это та же команда.
  • Если FILENAME не является полным путем к файлу, команда будет искать файл в каталогах, указанных в $PATH среды $PATH . Если файл не найден в $PATH , команда будет искать файл в текущем каталоге.
  • Если заданы какие-либо ARGUMENTS , они станут позиционными параметрами для FILENAME .
  • Если FILENAME существует, source выхода source команды равен 0 , в противном случае, если файл не найден, он вернет 1 .

Примеры команды source

В этом разделе мы рассмотрим несколько основных примеров использования source команды.

Функции поиска

Если у вас есть сценарии оболочки, использующие те же функции, вы можете извлечь их в отдельный файл, а затем указать этот файл в своих сценариях.

В этом примере мы создадим файл, который включает функцию bash, которая проверяет, является ли пользователь, запускающий скрипт, корневым, и если нет, он показывает сообщение и завершает скрипт.

Теперь в каждом скрипте, который должен запускаться только пользователем root, просто укажите файл functions.sh и вызовите функцию:

Если вы запустите приведенный выше сценарий как пользователь без полномочий root, он напечатает «Этот сценарий должен быть запущен от имени пользователя root» и завершится.

Преимущество этого подхода заключается в том, что ваши сценарии будут меньше и более читабельны, вы можете повторно использовать один и тот же файл функции, когда это необходимо, а в случае, если вам нужно изменить функцию, вы отредактируете только один файл.

Файл конфигурации Bash

С помощью source команды вы также можете читать переменные из файла. Переменные должны быть установлены с использованием синтаксиса Bash, VARIABLE=VALUE .

Создадим тестовый файл конфигурации:

В вашем сценарии bash используйте команду source для чтения файла конфигурации:

Если вы запустите сценарий, результат будет выглядеть так:

Выводы

В этом руководстве вы узнали, как использовать встроенную команду source в сценариях оболочки.

Если у вас есть какие-либо вопросы или отзывы, не стесняйтесь оставлять комментарии.

Источник

Оцените статью