Wednesday, 13 May 2020

Bash Script - return value in bash functions

These are my findings while exploring various ways of return values in Bash functions

1. return value is stored in $?. So we have to first call the function and extract return value from the exit status
function func1() {
  echo "return value is stored in '$?'"
  myvar1=dev1
#  return myvar1 - this is not allowed. Only a numerical return value is allowed
  myvar1=22
  return $myvar1
}

func1
val1=$?
echo "result1: $val1"
# result1: 22

2. modify a global variable to serve as 'return value'
function func2() {
  echo "modify global variable to serve as return value"
  myvar2=dev2
}

func2
val2=$myvar2
echo "result2: $val2"
# result2: dev2

3. write to stdout and capture the value in a variable. this works only if you have one echo in the function. otherwise all the echo statements are concatenated as function output.
function func3() {
  echo "write to stdout and capture value in var"
  local myvar3=dev3
  echo "$myvar3"
}

val3="$(func3)"
echo "result3: $val3"
# result3: write to stdout and capture value in var dev3


Monday, 4 May 2020

Dump and Restore Data from Postgres Tables

Following command can be used to dump entire tables into a .dmp file. This command does not take 'where' arguments. No filtering is done per table. The entire table will get dumped. The namespace field -n is optional. Fully qualify the table with a schema name if the table is in a particular schema other than public. eg schema.tablename. Multiple tables can be specified with multiple -t flags. 
pg_dump -h localhost -U username -d databasename -n namespace -a -t tablename1 -t tablename2 > sometables.dmp

This output file is a plain text file with a series of SQL COPY commands that can be used to recreate the table possibly in a different machine. 
To restore the file to a different machine, scp the file over to another box and use the following command to restore the tables in the file. The -f option gives the filename.
psql -h localhost -U username -d databasename -n namespace -1 -f sometables.dump