Что делает «источник»?

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

Он существует и работает. Почему в Ubuntu нет документации по этому поводу? Что оно делает? Как я могу установить документацию об этом?

511
связанные: http://superuser.com/questions/176783/what-is-the-difference-between-executing-a-bash-script-and-sourcing-a-bash-script/176788#176788 lesmana 13 лет назад 4
вы забыли `$ type source`` source это встроенная оболочка` bnjmn 10 лет назад 45
Моя оболочка возвратила встроенные команды `$ whatis source`` source (1) - bash, см. Bash (1) `. Кроме того, `man source` ведет меня на страницы руководства` BASH_BUILTINS (1) `. Это на Fedora, кстати, не знаю, почему эти пакеты Debian не (или плохо) не документированы. arielnmz 9 лет назад 1
@lesmana, отличная ссылка. Этот [связанный ответ] (http://superuser.com/a/176788/57649) является более полным ответом на этот вопрос. Scott 9 лет назад 2
Попробуйте "источник помощи" Jasser 8 лет назад 1
`source --help` - хорошее начало. Thorbjørn Ravn Andersen 6 лет назад 0

11 ответов на вопрос

420
nagul

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

Syntax

. filename [arguments] source filename [arguments] 
`Source` - это команда, специфичная для bash, или она есть в других оболочках? (Я прошу получить метки прямо на вопрос ...) Jonik 14 лет назад 5
Afaik, «источник» присутствовал в оболочке Борна и, следовательно, вероятно, присутствовал во всех ее потомках. http://en.wikipedia.org/wiki/Bourne_shell. Я знаю, что не все оболочки имеют команду `source`, менее уверенную в том, какие оболочки содержат ее. nagul 14 лет назад 2
@nagul, `source` не присутствовал в оболочке Bourne, это расширение GNU, появившееся значительно позже. Оригинальный и все еще переносимый синтаксис (POSIX) должен использовать команду «точка», то есть `.` вместо. Я лично никогда не использую `source`, учитывая тот факт, что он дольше печатается и не имеет добавленной стоимости. Я предполагаю, что его основная цель - сделать скрипты более читабельными для новичков. jlliagre 10 лет назад 11
@jlliagre Моя личная "объяснить, почему есть источник" заключается в том, что "источник" не только более нагляден, но и выглядит как опечатка. У меня были люди, пропускающие точку / точку, когда я посылаю технические команды по электронной почте. Rich Homolka 10 лет назад 16
Одно из распространенных применений этой команды - сценарий оболочки для `source` в« файле конфигурации », который содержит в основном назначения переменных. Затем присваивания переменных управляют вещами, которые выполняет остальная часть скрипта. Конечно, хороший скрипт установит переменные в разумные значения по умолчанию перед `source`, или, по крайней мере, проверит допустимые значения. LawrenceC 10 лет назад 3
Таким образом, на самом деле `.` является исходной командой, а` source` является синонимом / псевдонимом для нее. helt 6 лет назад 1
241
damphat

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

https://askubuntu.com/questions/182012/is-there-a-difference-between-and-source-in-bash-after-all?lq=1

Вы смешиваете ./command и. скрипт. команда-источник такая же, как.-команда. Использование ./meh говорит, что запускает скрипт / бинарный файл с именем meh в текущем каталоге и не имеет ничего общего с источником /. -command. Как поясняется в ответе по вашей ссылке. Joakim Elofsson 10 лет назад 24
@JoakimElofsson Это упомянуто в ссылке, но я изменю ответ, чтобы избежать неправильного понимания. Пожалуйста, исправьте это. damphat 10 лет назад 2
Довольно важно, чтобы принятый ответ также указывал на этот, потому что на мгновение я подумал, что `./ == source == .` Daniel F 6 лет назад 1
82
micans

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.

Всегда читайте что-то новое, когда читаете `man`) 10 лет назад 1
Вы также можете использовать `help `, то есть `help source`. LawrenceC 10 лет назад 17
`help` не работает везде (по крайней мере, в zsh). `type` делает. kumar_harsh 10 лет назад 1
Для усиления: если вы используете bash, и если вы знаете (возможно, через 'type'), что это встроенная команда, то 'help' приведет вас прямо к нужному абзацу документации, не пробираясь через 4 184 строки ' Человек Баш 'текст. Ron Burk 9 лет назад 2
34
Jawa

. (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 '.'.

From Bash man page:

. 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. 
20
Joakim Elofsson

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

source ~/.bashrc 

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

Short version would be:

. ~/.bashrc 

The man page:

. 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 short 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. 
Это должен быть принятый ответ. Peter Mortensen 7 лет назад 0
18
Harsh Vakharia

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

sourceУ команды есть синоним . filename.

Чтобы сделать это более понятным, взгляните на следующий скрипт, который устанавливает псевдоним.

make_alias

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

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

Опция 1: ./make_alias

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

chmod +x make_alias 

казнить

./make_alias 

проверить

alias 

Выход

**nothing** 

Упс! Псевдоним ушел с новой оболочкой.

Пойдем со вторым вариантом.

Вариант 2: source make_alias

казнить

source make_alias 

или же

. make_alias 

проверить

alias 

Выход

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

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

5
Akshay Upadhyaya

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. 
Не могли бы вы предоставить больше, чем просто RTFM? Peter Mortensen 7 лет назад 0
3
Jasser

Введите команду «источник помощи» в вашей оболочке.

Вы получите вывод, как это:

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. 
2
Alexandro de Oliveira

Из Проекта документации Linux, Расширенное руководство по написанию сценариев Bash,
Глава 15 - Внутренние команды и встроенные функции :

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

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

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

$ source $filename $arg1 arg2 
Чем этот ответ отличается от 9 предыдущих ответов? Stephen Rauch 6 лет назад 0
Я добавляю другой источник информации и дополнительную информацию, не упомянутую ранее. Alexandro de Oliveira 6 лет назад 1
1
w17t

Следует отметить, что хотя и являются удивительной команда, ни, sourceни его сокращенным из .будет источник более одного файла, значение

source *.sh 

или же

. script1.sh script2.sh 

не будет работать

Мы можем прибегнуть к использованию forциклов, но он будет многократно запускать исполняемый файл, создавая несколько команд или выпуская его.

Вывод: sourceне принимает несколько файлов в качестве входных данных. Аргумент должен быть один.

Который ИМХО отстой.

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