Home > Blockchain >  How to return file path instead of file contents in a bash function?
How to return file path instead of file contents in a bash function?

Time:05-24

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!

CodePudding user response:

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.

  •  Tags:  
  • bash
  • Related