Starlight_NL
Starlight_NL

Reputation: 81

How to use a text file for multiple variable in bash

I want to make an bash script for things I use much and for easy access of things but I want to make an firstrun setup that saves the typed paths to programs or commands in a txt file. But how can I do that. And how can I include the lines of the text file to multiple variables?

After a lot of testing I could use the 2 anwsers given. I need to store a variable directly to a textfile and not asking a user for his details and then stores that to a file So I want it to be like this

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

I really want to have an anwser to this because I want to script bash. I already experience in bash scripting.

Upvotes: 0

Views: 246

Answers (2)

dpp
dpp

Reputation: 1758

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

Upvotes: -1

that other guy
that other guy

Reputation: 123410

Here's an example:

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

The first time this script is run, it will ask the user for their name and save it. The next time, it will load the name from the file instead of asking.

Upvotes: 2

Related Questions