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

时间:2014-01-04 21:09:38

标签: bash

我想为我使用的东西做一个bash脚本,并且为了方便访问,但是我想做一个firstrun设置,将类型路径保存到txt文件中的程序或命令。但是我该怎么做呢如何将文本文件的行包含在多个变量中?

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

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脚本。

2 个答案:

答案 0 :(得分:2)

以下是一个例子:

#!/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!"

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

答案 1 :(得分:-1)

#!/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