0

I have a bash function within a sub shell that downloads a file from an s3 bucket and stores it within a json file:

download_file(){(
  fileName="$(mktemp)__trigger.json"
  aws_response="$(aws s3api get-object --version-id $VERSION_ID --bucket $BUCKET_NAME --key=$OBJECT_NAME $fileName | jq -cj)"
  if [[ -s "$fileName" ]]; then
      log_error "Unable to download file!"
      return 1
  fi
  log_info "[success] downloaded file"
  echo -n "$fileName"
);}

However, when I call this function from my main script and then echo out the return value, it returns the contents of the file rather than the path to the file:

downloadedFileName="$(download_file)"

echo "$downloadedFileName"

I am still a novice in bash and am looking for a way to alter this code to return the path of the temporary file that I downloaded rather than the contents of the file when I echo it out. Any help would be greatly appreciated!

oguz ismail
  • 1
  • 16
  • 47
  • 69
Jengels
  • 440
  • 6
  • 15
  • What part of your function do you think stores the downloaded content in the file? – Charles Duffy May 23 '22 at 01:34
  • The ```s3api get-object``` [should store it within](https://www.gcptutorials.com/post/how-to-download-an-object-from-amazon-s3-using-aws-cli) ```$fileName``` I believe. – Jengels May 23 '22 at 02:55
  • Ahh -- rereading, I see the filename being passed as a parameter. Missed that on the first pass. – Charles Duffy May 23 '22 at 02:56
  • I agree, it should behave as described. The jq call isn't doing anything because the data isn't being written to stdout and so isn't going through the pipeline, but that's relatively inconsequential. – Charles Duffy May 23 '22 at 02:58
  • Have you considered using `set -x` to trace your script? That way you can see exactly which output each individual line generates. – Charles Duffy May 23 '22 at 02:58
  • bash functions - despite of their name - don't really **return** anything. They can produce standard output and standard error, and set an 8-bit-return code, and that's it basically. You are catching standard output of your function, and we don't know what `log_error` and `log_info` is producing. These are the only candidates (besides `echo`) which may effect the standard output. Consider as alternative passing to your function the name of a bash variable, which is going to receive the file name to be generated. – user1934428 May 23 '22 at 10:53

1 Answers1

1

Please refer to How to return a string value from a Bash function for other suggestions on how to tackle. The easiest way to handle this is just use fileName somewhere else in your script. It will maintain the filename value that you want.

2ps
  • 15,099
  • 2
  • 27
  • 47