У меня есть сценарий оболочки, который не выполняется с ./ script.sh
, но требует . ./script.sh
для выполнения.
В чем разница между ./
и . ./
? Я использую среду MSYS2 в Windows. Обратите внимание на расстояние между точками. Я знаю, что делает ../
, и это не решает проблему, поскольку я нахожусь в том же каталоге, что и мой исполняемый файл.
Вот результат:
Они совершенно разные и не могут быть по сравнению.
./
означает текущий каталог.
. ./
ничего подобного не означает, при запуске будет выдана следующая ошибка:
-bash: .: ./: is a directory
Однако ее необходимо разбить на две части:
.
команда ./
.
команда - это встроенная оболочкав котором является синонимом команды source
. Он принимает в качестве параметра файл, а не каталог, поэтому вы получите ошибку, указанную выше.
Вы могли видеть очень похожий пример команды:
$ . ~/.bashrc
И это в точности синоним
$ source ~/.bashrc
Вы можете найти их руководство , запустив
man bash-builtins
. 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, filenames 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.
.
является оператором исходного кода в Bash и многих других оболочках POSIX:
$ help .
.: . 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.
Всегда безопаснее делать . ./script
вместо . скрипт
, потому что .
по умолчанию выполняет поиск в PATH, и вы можете столкнуться с конфликтами имен:
$ echo echo hi > script
$ . script
bash: .: /usr/bin/script: cannot execute binary file
$ . ./script
hi
И поскольку некоторые оболочки не выполняют поиск в текущем каталоге, по умолчанию:
$ mv script script-to-be-sourced
$ dash
$ . script-to-be-sourced
dash: 1: .: script-to-be-sourced: not found