为什么我的 bash 脚本没有导出到我的环境?

Why is my bash script not exporting to my environment?

我有一个简单的小 bash 脚本,它会要求输入密码并将其导出到环境中:

printf "Proxy authentication failed.\n"
read -p "Enter Password to try again: " mypassword
printf "Proxy authentication succeeded\n"
export PASSWORD="mypassword"

但是当我尝试 运行 它时,它不会导出到环境中:

baal@baal-Aspire-5733Z:/tmp$ sh vaWfKh.sh
Proxy authentication failed.
Enter Password to try again: test
Proxy authentication succeeded
baal@baal-Aspire-5733Z:/tmp$ printenv
CLUTTER_IM_MODULE=xim
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=00:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arc=01;31:*.arj=01;31:*.taz=01;31:*.lha=01;31:*.lz4=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.tzo=01;31:*.t7z=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;
...
XDG_CONFIG_DIRS=/etc/xdg/xdg-ubuntu:/etc/xdg
PATH=/home/baal/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin:/home/baal/.rvm/bin:/home/baal/.rvm/bin
LESSOPEN=| /usr/bin/lesspipe %s
GTK_IM_MODULE=ibus
_=/usr/bin/printenv

如何通过 bash 脚本导出到环境变量?

您需要 source 脚本或 运行 . 在它前面,以便在脚本期间导出变量 -

注意:您需要插入 mypassword 变量才能将其设置为您的环境变量。

假设这是你的 ./myscript.sh

#!/bin/bash

printf "Proxy authentication failed.\n"
read -p "Enter Password to try again: " mypassword
printf "Proxy authentication succeeded\n"
export PASSWORD=${mypassword}

在您的终端 运行 中:

. ./myscript.sh

source ./myscript.sh