What does the command 'source' do?

空扰寡人 提交于 2021-02-13 17:39:10

问题


I would like to know what does the command source do. I have tried:

  • whatis
$ whatis source
source: nothing appropriate.
  • man
$ man source
No manual entry for source
  • source (-h, --help, etc...)
$ source
source: not enough arguments

But it seems no documentation about it.

I commonly use it to save any changed on my dotfiles, but what does it exactly do? Why there is not documentation about it?


回答1:


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).

Syntax

. filename [arguments]

source filename [arguments]

From the source manual

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. 

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

Is there any difference between source in bash after all?



来源:https://stackoverflow.com/questions/56161291/what-does-the-command-source-do

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!