Source in linux shell scripts

What does ‘source’ do?

It exists, and it is runnable. Why isn’t there any documentation about it in Ubuntu? What does it do? How can I install documentation about it?

My shell returned this $ whatis source source (1) — bash built-in commands, see bash(1) . Also, man source takes me to the BASH_BUILTINS(1) man pages. This is on Fedora btw, no idea why those debian packages are un-(or badly)-documented.

12 Answers 12

source is a Bash shell built-in command that executes the content of the file passed as an argument in the current shell. It has a synonym in . (period).

. filename [arguments] source filename [arguments] 

Is source a bash specific command or do other shells have it too? (I’m asking to get tags right on the question. )

Afaik, source was present in the Bourne shell and hence probably present in all its descendants. en.wikipedia.org/wiki/Bourne_shell. I know that not all shells have the source command, less certain about which shells do contain it.

@nagul, source was not present in the Bourne shell, it is a GNU extension that came much later. The original and still portable syntax (POSIX) is to use the «dot» command, i.e. . instead. I personnaly never use source given the fact it is longer to type and has no added value. I guess its main purpose is to make scripts more readable for newbies.

@jlliagre my personal «explain why have source» is that source is not only more descriptive, but it looks like something other than a typo. I’ve had people skip the period/dot when I send tech commands in email.

One common use for this command is for a shell script to source in a «configuration file» that contains mostly variable assignments. The variable assignments then control things the rest of the script does. Of course, a good script will set variables to sensible defaults before the source , or at least check for valid values.

Be careful! ./ and source are not quite the same.

  • ./script runs the script as an executable file, launching a new shell to run it
  • source script reads and executes commands from filename in the current shell environment

Note: ./script is not . script , but . script == source script

You are mixing up ./command and . script. source-command is same as .-command. Using ./meh says run script/binary named meh in the current directory, and got nothing to do with source/. -command. As explained in answer in your link.

@JoakimElofsson It is mentioned in the link, but I will modify the answer to avoid missunderstand. Please correct it.

It’s kind of important that the accepted answer also points to this one, because for a moment I thought that ./ == source == .

It is useful to know the ‘type’ command:

> type source source is a shell builtin 

whenever something is a shell builtin it is time to do man bash .

To amplify: if you are using bash, and if you know (perhaps via ‘type’) it is a built-in command, then ‘help’ will get you directly to the paragraph of documentation you want without wading through 4,184 lines of ‘man bash’ text.

Читайте также:  Установка samsung ml 1210 linux

. (a period) is a bash shell built-in command that executes the commands from a file passed as argument, in the current shell. ‘source’ is a synonym for ‘.’.

. filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command exe‐ cuted from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing file‐ name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the posi‐ tional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. 

‘source’ is the long version of ‘.’ command. On the bash prompt one can do:

to reload your (changed?) bash setting for current running bash.

. filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. 

source command executes the provided script (executable permission is not mandatory) in the current shell environment, while ./ executes the provided executable script in a new shell.

source command do have a synonym . filename .

To make it more clear, have a look at the following script, which sets the alias.

make_alias

#! /bin/bash alias myproject='cd ~/Documents/Projects/2015/NewProject' 

Now we have two choices to execute this script. But with only one option, the desired alias for current shell can be created among these two options.

Option 1: ./make_alias

Make script executable first.

Execute

Verify

Output

Whoops! Alias is gone with the new shell.

Let’s go with the second option.

Option 2: source make_alias

Execute

Verify

Output

alias myproject='cd ~/Documents/Projects/2015/NewProject' 

Yeah Alias is set.

When in doubt, the best thing to do is use the info command:

[root@abc ~]# info source BASH BUILTIN COMMANDS Unless otherwise noted, each builtin command documented in this section as accepting options preceded by - accepts -- to signify the end of the options. The :, true, false, and test builtins do not accept options and do not treat -- specially. The exit, logout, break, continue, let, and shift builtins accept and process arguments beginning with - with- out requiring --. Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with - as invalid options and require -- to prevent this interpretation. : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned. . filename [arguments] source filename [arguments] Read and execute commands from filename in the current shell environment and return the exit status of the last command exe- cuted from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing file- name. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the posi- tional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read. 

Источник

Читайте также:  Командный файл bash linux

Команда source в Linux

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

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

Команда source linux

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

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

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

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

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

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

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

Читайте также:  Налоговая личный кабинет linux

source losstsource losst.pro

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

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

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

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

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

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

Выводы

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

Обнаружили ошибку в тексте? Сообщите мне об этом. Выделите текст с ошибкой и нажмите Ctrl+Enter.

Источник

How to use source command in shell script?

command doesn’t show anything. So, source is not the normal command? Is this wrong idea? or how can I reduce the type of path?

Quick answer: source is BASH SHELL BUILTIN command. See man bash (search for » source filename [arguments] » to find it). It doesn’t work in question probably because you are using the SH shell (something besides BASH anyway) as your login shell, or inside your script. Use BASH if you want the source command.

3 Answers 3

source is a shell built-in command. The which command looks for binaries on the PATH , like in /usr/bin, /bin, /sbin, etc. but you won’t find any built-in commands in a separate binary.

Also, having the source command in a shell script does not result in the source propagating up to your current shell when you run it. sh blah.sh where blah.sh has source in it will not actually source the contents of the file into your interactive shell. That’s not how sourcing works.

If you want this sourcing of the tensorflow activate script to happen every time you open a new shell, you need to edit ~/.bashrc or ~/.profile (or other files, depending on what your shell is and how it’s configured) and put the source` command directly in there.

P.S. — your question title is very confusing and looks incomplete. Take some time to edit, revise and clean up your post, or you run the risk of someone downvoting it 😛 I’m tempted to do so myself, but I wrote an answer, so I’m a little bias.

Источник

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