Что делает «источник»?
$ whatis source
source: nothing appropriate.
$ man source
No manual entry for source
$ source
bash: source: filename argument required
source: usage: source filename [arguments]
Он существует, и он запускается. Почему в Ubuntu нет документации по этому поводу? Что оно делает? Как я могу установить документацию об этом?
10 ответов
source
- это встроенная команда оболочки bash, которая выполняет содержимое файла, переданное как аргумент, в текущей оболочке . Он имеет синоним в .
(period).
Синтаксис
. filename [arguments] source filename [arguments]
Будьте осторожны! ./
и source
являются не совсем одинаковыми .
-
./script
запускает скрипт как исполняемый файл, запуская новую оболочку для ее запуска -
source script
читает и выполняет команды из имени файла в среде текущая оболочка
Примечание: ./script
не . script
, но . script
== source script
Полезно знать команду «type»:
> type source
source is a shell builtin
всякий раз, когда что-то является встроенной оболочкой, пришло время сделать man bash
.
. (период) представляет собой встроенную команду оболочки bash , которая выполняет команды из файла, переданного в качестве аргумента, в текущей оболочке. «источник» - синоним «.».
На странице пользователя 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 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' - это длинная версия '.' команда. В командной строке можно сделать:
source ~/.bashrc
, чтобы перезагрузить вашу (измененную?) настройку bash для текущего запуска bash.
Короткий вариант:
. ~/.bashrc
Страница руководства:
. 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.
source
выполняет исполняемый скрипт (допустимое разрешение не обязательно ) в среде текущей оболочки, а ./
выполняет выполняемый сценарий исполняемый в новой оболочке.
source
имеет синоним . filename
.
Чтобы сделать это более понятным, просмотрите следующий скрипт, который устанавливает псевдоним.
make_alias
#! /bin/bash
alias myproject='cd ~/Documents/Projects/2015/NewProject'
Теперь у нас есть два варианта выполнения этого скрипта. Но с помощью only один из вариантов может быть создан желаемый псевдоним для текущей оболочки.
Вариант 1: ./make_alias
Сначала выполнить скрипт.
chmod +x make_alias
Execute
./make_alias
Verify
alias
Выход
нет**nothing**
Упс! Псевдоним ушел с новой оболочкой.
Перейдем ко второй опции.
Вариант 2: source make_alias
Execute
source make_alias
или
. make_alias
Verify
alias
Выход
alias myproject='cd ~/Documents/Projects/2015/NewProject'
Да, Установлено псевдоним.
Если у вас есть сомнения, лучше всего использовать info
:
[[email protected] ~]# 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.
Введите команду «справочный источник» в своей оболочке.
Вы получите результат следующим образом:
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.
Из проекта документации Linux, Руководство по разработке сценариев Advanced Bash,
Глава 15 - Внутренние команды и встроенные функции :
источник , . (команда dot):
Эта команда при вызове из командной строки выполняет скрипт. В сценарии исходное имя файла загружает имя файла. Поиск файла (dot-command) импортирует код в скрипт, добавляя к скрипту (тот же эффект, что и директива #include в программе C). Конечный результат такой же, как если бы «исходные» строки кода физически присутствовали в тексте сценария. Это полезно в ситуациях, когда несколько сценариев используют общий файл данных или библиотеку функций.
Если исходный файл сам по себе является исполняемым скриптом, он запускается, а затем возвращает управление сценарию, который его вызывал. Исполняемый сценарий с исходным кодом может использовать возврат для этой цели.
Итак, для тех, кто знаком с языком программирования C, поиск файла имеет эффект, аналогичный директиве #include
.
Обратите также внимание на то, что вы можете передать позиционные аргументы в исходный файл, например:
$ source $filename $arg1 arg2
Следует отметить, что, хотя это была потрясающая команда, ни source
, ни его сокращение .
не могли бы source больше одного , что означает
source *.sh
или
. script1.sh script2.sh
работает не .
Мы можем вернуться с помощью циклов for
, но он многократно выдавал исполняемый файл, создавая несколько команд или выдавая их.
Заключение: source
не принимает несколько файлов в качестве входных данных. Аргумент должен быть одним.
Что отдает IMHO.