0

I have a text file with variables in format VARIABLE=value like:

PID=123123
WID=569569
TOKEN=456456456

Where VARIABLE has only uppercase letters and value contains only alphanumeric characters ([a-zA-Z0-9])

Now I want to pass these variables to a script as named arguments (options):

./script.sh --PID 123123 --WID 569569 --TOKEN 456456456

Is there a simple way to do this in bash?

I have read:

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    In the general case, `xargs` has problematic corner cases when the input file is large, but if it's just a few options, `sed 's/^/--/;s/=/ /' file | xargs ./script.sh` – tripleee Apr 11 '23 at 07:59
  • @jonrsharpe I'm not asking about environment variables – Konrad Apr 11 '23 at 08:04
  • 1
    Your question is unclear. You only give **example** definitions for variable, but not a precise definition of the syntax. Your example happens to look like `bash` variable definition, so if you would say that the text file's content simply is a piece of bash code, you could simply source the file using `source FILENAME`. This comes with all risks and perils of such an approach, i.e. as long as you are the one who prepares the "text file", you are safe, but if the file comes from a place outside of your control, you better do some parsing. – user1934428 Apr 11 '23 at 10:08
  • @user1934428 I added some constrains for the values to the question – Konrad Apr 11 '23 at 10:25
  • That's great. You should now add that there are no spaces allowed in this line. If this is the case, you can think of it as bash code, and simply source the file. In this case, you need to add to what extent you want the file to be syntax-checked. – user1934428 Apr 11 '23 at 10:49
  • One more point to consider is whether you are willing to exclude a certain set of "variable" names. If you forbid "dangerous" variable names, you could then (after sourcing) simply refer to the variables by name, i.e. `$PID` or `$TOKEN` in your example. If you want to have a foolproof solution which allows and upper-case-letter name as variable, you need to parse the file and store the name/value pairs into an associative array. You would then refer to them as, i.e., `${par[PID]}` or `${par[TOKEN]}`. Since I don't know your concrete application, I can't tell how much safety you need. – user1934428 Apr 11 '23 at 10:53
  • i always looking for simple answer so i suggest this: ```for i in $(cat /PATH/TO/txt_file_with_variables) ; do export $i ; done ``` after that you can run your command like this: ```./script.sh --PID $PID --WID $WID --TOKEN $TOKEN ``` – Elham_Jahani Apr 11 '23 at 14:08

1 Answers1

3

Read the file line by line as = separated elements and construct the array of arguments. Then call the script.

args=()
while IFS== read -r k v; do
   args+=("--$k" "$v")
done < yourtextfile.txt
./script.sh "${args[@]}"
KamilCuk
  • 120,984
  • 8
  • 59
  • 111