Linux中的源命令

Rod*_*wer 5 linux shell

我的问题是:
为什么如果我运行一些带有别名的文件,例如内容如下:

alias lsa="ls -a" 
Run Code Online (Sandbox Code Playgroud)

直接地:

$ ./aliases
Run Code Online (Sandbox Code Playgroud)

它不创建别名(可能仅在脚本上下文中)。
但是如果我用命令“source”运行它:

$ source aliases
Run Code Online (Sandbox Code Playgroud)

它起作用了吗?我的意思是在执行命令 shell 上下文中存在的别名“lsa”之后?
“man source”给出:“没有手动输入源代码”,在谷歌中我刚刚发现它运行Tcl,但为什么Tcl影响shell上下文和bush不?

m45*_*73r 7

基本上是因为当您运行时./aliases,它会创建一个进程,其中您的别名存在但随后立即结束,而当您运行source时,它适用于您当前的 bash 进程。

要获得帮助source,您需要阅读man bash. 为您省去麻烦:

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 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.
Run Code Online (Sandbox Code Playgroud)

  • 或`man csh`,视情况而定。 (2认同)

Nic*_*ton 5

当您将它作为可执行脚本运行时,shell 会派生一个自己的副本作为子进程来运行该脚本。这意味着对别名的任何更改:

  • 只会被那个孩子看到。
  • 孩子一出门就迷路了。

相比之下,当您source编写脚本时:

  • 它在同一进程中运行(就好像您只是输入了它的内容一样)
  • 保留对别名的更改。