如何在bash中为多个变量使用文本文件

如何在bash中为多个变量使用文本文件,bash,Bash,我想为我经常使用的东西制作一个bash脚本,以便于访问,但我想制作一个firstrun设置,将程序或命令的键入路径保存在一个txt文件中。但我该怎么做呢。如何将文本文件的行包含到多个变量中 经过大量测试后,我可以使用给定的2个ANWSER。我需要将一个变量直接存储到一个文本文件中,而不是询问用户的详细信息,然后将其存储到一个文件中 所以我希望它是这样的 if [[ -d "/home/$(whoami)/.minecraft" && ! -L "/home/$(whoami)/.

我想为我经常使用的东西制作一个bash脚本,以便于访问,但我想制作一个firstrun设置,将程序或命令的键入路径保存在一个txt文件中。但我该怎么做呢。如何将文本文件的行包含到多个变量中

经过大量测试后,我可以使用给定的2个ANWSER。我需要将一个变量直接存储到一个文本文件中,而不是询问用户的详细信息,然后将其存储到一个文件中 所以我希望它是这样的

if [[ -d "/home/$(whoami)/.minecraft" && ! -L "/home/$(whoami)/.minecraft" ]] ; then
    echo "Minecraft found"
    minecraft="/home/$(whoami)/Desktop/shortcuts/Minecraft.jar" > safetofile
    # This ^ needs to be stored on a line in the textfile
else
    echo "No Minecraft found"
fi

if [[ -d "/home/$(whoami)/.technic" && ! -L "/home/$(whoami)/.technic" ]]; then
    echo "Technic found"
    technic="/home/$(whoami)/Desktop/shortcuts/TechnicLauncher.jar" > safetofile
    # This ^ also needs to be stored on an other line in the textfile
else
    echo "No Technic found"
fi
我真的很想知道这个,因为我想编写bash脚本。我已经有过bash脚本编写的经验。

下面是一个示例:

#!/bin/bash
if [[ -f ~/.myname ]]
then
    name=$(< ~/.myname)
else
    echo "First time setup. Please enter your name:"
    read name
    echo "$name" > ~/.myname
fi
echo "Hello $name!"
#/bin/bash
如果[[-f~/.myname]]
然后
name=$(<~/.myname)
其他的
echo“首次安装。请输入您的姓名:”
读名字
回显“$name”>~/.myname
fi
echo“你好$name!”

第一次运行此脚本时,它将询问用户的姓名并将其保存。下次,它将从文件中加载名称,而不是询问。

感谢脚本@that\u other\u guy。但如果文件中有更多的文本行,这是否也有效。我想存储很多行,所有的行都需要分离变量。谢谢@dpp的反应。但是,如果您输入带有空格的文本,它将无法工作。你能给我解释一下吗?这样我就知道下次怎么用了。谢谢,我想这是不言自明的。请参阅更新的答案。这会给你一个好的开始。我还添加了一个带有空格的值检查。感谢您的解释。这真的对我有帮助@dpp
#!/bin/bash

# file to save the vars
init_file=~/.init_vars.txt

# save_to_file - subroutine to read var and save to file
# first arg is the var, assumes init_file already exists   
save_to_file()
{
    echo "Enter $1:"
    read val
    # check if val has any spaces in them, you will need to quote them if so
    case "$val" in
        *\ *)
            # quote with double quotes before saving to init_file 
            echo "$1=\"$val\"" >> $init_file
            ;;
        *)
            # save var=val to file
            echo "$1=$val" >> $init_file
            ;;
    esac
}

if [[ ! -f $init_file ]]
then
    # init_file doesnt exist, this will come here only once
    # create an empty init_file
    touch $init_file

    # vars to be read and saved in file, modify accordingly
    for var in "name" "age" "country"
    do
        # call subroutine
        save_to_file "$var"
    done
fi

# init_file now has three entries, 
# name=val1
# age=val2
# country=val3
# source the init_file which will read and execute commands from init_file,
# which set the three variables
. ${init_file}

# echo to make sure it is working
echo $name $age $country