2009-09-24 10:35:48 +0000 2009-09-24 10:35:48 +0000
604
604
Advertisement

Что делает 'source'?

Advertisement
$ whatis source
source: nothing appropriate.
$ man source
No manual entry for source
$ source
bash: source: filename argument required
source: usage: source filename [arguments]

Он существует, и он работает. Почему в Убунту нет никакой документации об этом? Что он делает? Как установить документацию о нем?

Advertisement

Ответы (9)

289
289
289
2013-07-11 13:24:07 +0000

Будьте осторожны! ./ и source - это не совсем одно и то же.

  • ./script запускает скрипт как исполняемый файл, запускает new shell для запуска
  • source script читает и выполняет команды из имени файла в current shell окружении

Замечание: ./script это не . script, но . script == source script https://askubuntu.com/questions/182012/is-there-a-difference-between-and-source-in-bash-after-all?lq=1

92
92
92
2013-01-09 15:45:47 +0000

Полезно знать команду ‘type’:

> type source
source is a shell builtin

всякий раз, когда что-то собирается в оболочку, пора делать man bash.

40
Advertisement
40
40
2009-09-24 10:48:52 +0000

. (a period) - это встроенная в оболочку bash shell команда , которая выполняет команды из файла, переданного в качестве аргумента, в текущей оболочке. Исходный код" является синонимом ‘.’.

Из Bash man:

. 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.
32
32
32
2009-09-24 10:46:01 +0000

Исходник" - это длинная версия команды ‘.’. В bash-запросе можно сделать:

source ~/.bashrc

, чтобы перезагрузить ваш (измененный?) bash-настройку для текущей выполняемой bash.

Краткая версия будет:

. ~/.bashrc

.

28
Advertisement
28
28
2015-03-27 13:57:39 +0000

Команда source выполняет предоставленный сценарий (разрешение на исполнение не обязательно ) в current shell окружении, в то время как команда ./ выполняет предоставленный сценарий executable в new shell. Команда

source имеет синоним . filename.

Для большей ясности посмотрите на следующий сценарий, который устанавливает псевдоним.

make_alias

#! /bin/bash

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

Теперь у нас есть два варианта выполнения этого сценария. Но с опцией only one, нужный псевдоним для текущего shell'а можно создать среди этих двух вариантов.

Вариант 1: ./make_alias

Сначала сделать скрипт исполняемым.

Выполнить

chmod +x make_alias

Проверить

./make_alias

Вывод

alias

*Whoops! * Псевдоним отсутствует в новой оболочке.

Перейдем ко второму варианту.

Вариант 2: source make_alias

Выполнить

**nothing**

or

source make_alias

Проверить

. make_alias

Выход

alias

Да Псевдоним установлен.

10
10
10
2015-11-11 05:44:49 +0000

В случае сомнений лучше всего использовать команду info :

[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.
```.
5
Advertisement
5
5
2015-09-19 14:14:57 +0000

Введите команду “help source” в вашем shell'е.

Вы получите следующий вывод:

source: source filename [arguments]

Execute commands from a file in the current shell.

Read and execute commands from FILENAME in the current shell. The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.

Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
4
4
4
2017-06-12 00:13:34 +0000

Из Linux Documentation Project, Advanced Bash Scripting Guide, Гл. 15 - Внутренние команды и сборки :

source , . (точечная команда): Эта команда, при вызове из командной строки, выполняет скрипт. Внутри скрипта имя файла-источника загружает имя файла. Источник файла (точечная команда) импортирует код в скрипт, добавляя его к скрипту (тот же эффект, что и при использовании директивы #include в программе на языке Си). Суммарный результат такой же, как если бы в теле скрипта физически присутствовали “исходные” строки кода. Это полезно в ситуациях, когда несколько сценариев используют общий файл данных или библиотеку функций. Если исходный файл сам по себе является исполняемым сценарием, то он выполнится, а затем вернет управление вызывающему его сценарию. Исходный исполняемый сценарий может использовать возврат для этой цели.

Таким образом, для тех, кто знаком с языком программирования C, поиск файла имеет эффект, аналогичный эффекту директивы #include.

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

$ source $filename $arg1 arg2
0
Advertisement
0
0
2018-11-28 08:58:53 +0000

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

F.I:

#!/bin/bash

source /etc/environment

source /myscripts/jetty-common/config/jetty-functions.sh

Спасибо.

Похожие вопросы

6
10
37
6
9
Advertisement
Advertisement