2

I have

SA_PASSWORD=Password1! 

in a file, tests/.makefile_test_env. I would like to get the value "Password1!" into a variable on my bash shell. I tried this

$ MY_VAR=$(grep SA_PASSWORD tests/.makefile_test_env | xargs) 

Unfortunately, this returns

$ echo $MY_VAR SA_PASSWORD=Password1! 

How do I filter out the "SA_PASSWORD=" part?

0

3 Answers 3

1

You can do this doing the cut command; keep in mind, though, it may not be a good idea to keep passwords inside of scripts.

[ekaj@headdesk ~]$ cat vars SA_PASSWORD=Password1! [ekaj@headdesk ~]$ cat setvar.sh #!/bin/bash echo "MY_VAR is currently set to: $MY_VAR" MY_VAR=$(grep SA_PASSWORD ./vars | cut -d'=' -f 2-) echo "MY_VAR is currently set to: $MY_VAR" [ekaj@headdesk ~]$ [ekaj@headdesk ~]$ ./setvar.sh MY_VAR is currently set to: MY_VAR is currently set to: Password1! [ekaj@headdesk ~]$ 

The -f 2- prints all fields after the first =, which might be handy if your password happens to have an equals sign in it.

1

If the name of the variable doesn't matter you could source it.

source tests/.makefile_test_env echo $SA_PASSWORD # Prints Password1! 

WARNING: Performing source on an untrusted file is dangerous. You're executing a shell script, and that script can perform anything you could do yourself.

0

You almost have it, try using extended regex and the look behind pattern and only (also you don't need the pipe to xargs):

MY_VAR=$(grep -Po '(?<=SA_PASSWORD=).*' tests/.makefile_test_env) 

This says:

  1. Make a shell variable called 'MY_VAR' and set it to whatever comes out of $() which is...
  2. grep using -P perl regex and -o only return the match for this pattern '...' which is
  3. (?<=SA_PASSWORD=).* this means match any character any number of times .*, but only if the characters just before (?<=) the first . are 'SA_PASSWORD=' oh and don't include them as part of the match.

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.