user123328
user123328

Reputation: 63

Set User Name and Password from Txt file using bash

I have an env.txt file in the following format:

lDRIVER={ODBC Driver 13 for SQL Server};
PORT=1433;
SERVER=serveename;
DATABASE=db;
UID=username;
PWD=password!

I have a git bash script (.sh) that requires the UID and PWD from that file. I was thinking about getting it by the last/second last line number. How do I do this/ is there a better way (say looking for UID and PWD and assigning the git bash variable that way)

Upvotes: 0

Views: 1012

Answers (2)

Walter A
Walter A

Reputation: 20002

First rename PWD to something like PASSWORD. PWD is a special variable used by the shell. Even better is to use lowercase variable names for all your own variables.

When the password is without special characters (spaces, $, ), you can

source env.txt

When the password has something special, consider editing the env.txt:

lDRIVER="{ODBC Driver 13 for SQL Server}"
PORT="1433"
SERVER="serveename"
DATABASE="db"
UID="username"
PASSWORD="password!"

When you are only interested in lowercase uid and passwd, consider selecting only the interesting fields and change the keywords to lowercase

source <(sed -rn '/^(UID|PWD)=/ s/([^=]*)/\L\1/p' env.txt)

Upvotes: 1

JNevill
JNevill

Reputation: 50034

There's lots of ways to do this. You could use awk which I would personally use since it's sort of like an x-acto knife for this type of thing:

uid=$(awk -F"[=;]" '/UID/{print $2}' env.txt)
pwd=$(awk -F"[=;]" '/PWD/{print $2}' env.txt)

Or grep and sed. sed is nice because it allows you to get very specific about the piece of info you want to cut from the line, but it's regex which has its learning curve:

uid=$(grep "UID" env.txt | sed -r 's/^.*=(.*)(;|$)/\1/g' )
pwd=$(grep "PWD" env.txt | sed -r 's/^.*=(.*)(;|$)/\1/g' )

As @JamesK noted in the comments you can use sed and have it do the search instead of grep. This is super nice and I would definitely choose this instead of the grep | sed.

uid=$(sed -nr '/UID/s/^.*=(.*)(;|$)/\1/gp' )
pwd=$(sed -nr '/PWD/s/^.*=(.*)(;|$)/\1/gp' )

Or grep and cut. Bleh... we can all do better, but sometimes we just want to grep and cut and not have to think about it:

uid=$(grep "UID" env.txt | cut -d"=" -f2 | cut -d";" -f1)
pwd=$(grep "PWD" env.txt | cut -d"=" -f2 | cut -d";" -f1)

I definitely wouldn't go by line number though. That looks like and odbc.ini file and the order in which the parameters are listed in each odbc entry are irrelevant.

Upvotes: 1

Related Questions