How to save entered values in Bash

Use a file and the declare command to ask information only once

Author's image
Tamás Sallai
1 min

Input values

I use a dotfiles folder that sets up my development environment with all the tools and config I need for my work. One thing it does is it sets up a gitconfig file which is required to use git.

It needs a name and an email, and it has a trivial structure:

	name = ...
	email = ...

As I don't want to hardcode them the install script asks for these values:

read -p "Git username: " GIT_NAME
read -p "Git email: " GIT_EMAIL

When I enter these data, the script can go on and initialize the gitconfig.

The problem is, when I run it again it asks for the same info again. While it could parse the gitconfig, I wanted a solution that works with all sorts of other services. So it should save the GIT_NAME and the GIT_EMAIL values somewhere and reuse them the next time the script runs.


Bash has a function that prints the command that initializes a variable to its current value by outputting a declare command:


This prints:

declare -- GIT_NAME=""
declare -- GIT_EMAIL=""

Note: The -- means the type of the variable is not defined (string).

These commands restore the GIT_NAME and the GIT_EMAIL variables with their entered values.

Putting it together

With this, a simple solution is possible. It has three parts.

First, if a file with the saved variables exists, load it:

if [ -f "git/.saved_variables" ];
	. git/.saved_variables

Then check if the required values are present, and if not, prompt for them:

if [[ -z "$GIT_NAME" ]];
	read -p "Git username: " GIT_NAME

if [[ -z "$GIT_EMAIL" ]];
	read -p "Git email: " GIT_EMAIL

And finally, save the current values to the file:

declare -p GIT_NAME GIT_EMAIL > git/.saved_variables

This way, the script only asks for info the first time it runs, then the next time everything is automated.

May 17, 2022
In this article