CatCoding

Linux 当前 shell 执行命令

2018-02-22

Linux shell 执行脚本的时候一般是会 fork 出一个子 shell,这样在有的时候就不方便了,比如要 unset 当前 shell 的环境变量等,

#!/usr/bin/env zsh

if [ -z $http_proxy ]; then
    echo "not using proxy, set it now ... ";
    export http_proxy="http://127.0.0.1:1087";
    export https_proxy="https://127.0.0.1:1087";
    echo $http_proxy;
else
    echo "using proxy now, unset it now ...";
    unset http_proxy;
    unset https_proxy;
    echo $http_proxy;
fi

这时候需要执行 . ./proxy_toggle.sh 或者 source ./proxy_toggle.sh

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

公号同步更新,欢迎关注👻