在bash脚本中设置本地环境变量

时间:2013-11-04 18:29:44

标签: linux bash shell scripting

我正在尝试设置一个在脚本运行完毕后会持续存在的环境变量。在我结束ssh会话后,它可能会消失。

示例bash脚本:

# User picks an option
1) export dogs = cool
2) export dogs = not_cool

将脚本作为source script.sh运行不起作用,因为它在运行时将我从shell中踢出来,并且还需要交互式菜单,因此它不起作用。基本上我希望用户能够选择在shell中切换环境变量的选项。这甚至可能吗?

来源:

#!/bin/bash
set -x
show_menu(){
    NORMAL=`echo "\033[m"`
    MENU=`echo "\033[36m"` #Blue
    NUMBER=`echo "\033[33m"` #yellow
    FGRED=`echo "\033[41m"`
    RED_TEXT=`echo "\033[31m"`
    ENTER_LINE=`echo "\033[33m"`
    echo -e "${MENU}*********************************************${NORMAL}"
    echo -e "${MENU}**${NUMBER} 1)${MENU} Option 1 ${NORMAL}"
    echo -e "${MENU}**${NUMBER} 2)${MENU} Option 2 ${NORMAL}"
    echo -e "${MENU}*********************************************${NORMAL}"
    echo -e "${ENTER_LINE}Please enter a menu option and enter or ${RED_TEXT}enter to exit. ${NORMAL}"
    read opt
}
function option_picked() {
COLOR='\033[01;31m' # bold red
RESET='\033[00;00m' # normal white
MESSAGE=${@:-"${RESET}Error: No message passed"}
echo -e "${COLOR}${MESSAGE}${RESET}"
}
clear
show_menu
while [ opt != '' ]
do
    if [[ $opt = "" ]]; then
        exit;
    else
        case $opt in
            1) clear;
                option_picked "Option 1";
                export dogs=cool
                show_menu;
                ;;
            2) clear;
                option_picked "Option 2";
                export dogs=not_cool
                show_menu;
                ;;
            x)exit;
                ;;
            \n)exit;
                ;;
            *)clear;
                option_picked "Pick an option from the menu";
                show_menu;
                ;;
        esac
    fi
done

3 个答案:

答案 0 :(得分:0)

尝试使用“./myscript.sh”运行脚本,该脚本将使用当前shell而不调用新shell(我仍然怀疑哈希爆炸可能会调用新shell)。

Have a look here

也可以用〜/ .bashrc解决。可以在此文件中添加所需的环境。如果您需要具有自己环境的新shell,则使用“bash --rcfile”调用“bash”。

答案 1 :(得分:0)

这里的问题是. ./script.shsource ./script.sh无法像这样运行交互式菜单样式脚本。我不知道如何从bash脚本中设置本地环境变量,就像我在这里尝试一样。

答案 2 :(得分:0)

将用户互动的正常回音重定向到stderr(>& 2)

将您希望在父级环境中拥有的值回显到stdout(>& 1)

如果您以这种方式更改了脚本,则可以将其命名为:

ENV_VAR=$( /path/to/your_script arg1 arg2 arg3 arg_whatever )

现在你已经"导出"父母"

的变量