0

I have a file name inputfile having following data:

 database=mydb
 table=mytable
 partitions=p1,p2,p3

I pass this file as first argument as following:

 bash mybashfile.sh inputfile

I want to use this file in my bash script that input database, table and partitions as variables

I tried this by putting the whole content of myfile in a variable

  #!/bin/bash
  var=$(cat $1) 
  echo $var   

I am new to bash script so I need help

2 Answers2

3

Consider using source, which will load the variables from that file

#!/bin/bash
source "$1"
echo "$database"
# mydb
echo "$table"
# mytable
echo "$partitons"
# p1,p2,p3

For more information about source see this superuser-question

Mime
  • 1,142
  • 1
  • 9
  • 20
  • If I need to input these variables using yaml file like database: mydb table: MYTABLE partitions: p1,p2,p3 . Any idea how can I do that – Rahul Sharma Apr 21 '22 at 12:11
  • `source <(sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml)` would be a possible solution, but it is not that good or safe to use. Better use a tool like `yq`. For more information about parsing `yaml` to `bash` see this question https://stackoverflow.com/questions/5014632/how-can-i-parse-a-yaml-file-from-a-linux-shell-script – Mime Apr 21 '22 at 12:25
0

You can read key, value pairs from a file with a while loop:

#!/bin/bash
declare -A kv     # declare an associative array

while IFS="=" read -r k v; do
    kv["$k"]="$v"
done < "file"

declare -p kv     # print the array

Prints:

declare -A kv=([table]="mytable" [database]="mydb" [partitions]="p1,p2,p3" )
dawg
  • 98,345
  • 23
  • 131
  • 206