I'm trying to return a value from a function in bash using what I've seen here. But for some reason my script just hangs instead of returning a value from the function. What am I doing wrong (running on Ubuntu)?
#!/bin/bash
...
function check_ftp_file_exists {
local ftp_path=$1
echo "Checking whether remote path $ftp_path exists on FTP server $FTP_HOST..."
echo "ls $1" | sftp -b - -i $FTP_PEM_FILE ${FTP_USER}@${FTP_HOST}
echo "$?"
}
retval=$(check_ftp_file_exists $FILE_PATH)
echo "here retval is $retval" # never get here
-- update -- In the above, there seems to be an error with the SFTP command, even though I've lifted it from another script where it works correctly.
THe bigger problem for now though is that using '$()' seems to return anything that I echo inside a function, instead of just the return code of running the external command which is what I want.
E.g.
function exit_on_error {
local return_code=$1
local error_message=$2
if [[ $return_code -ne 0 ]]; then
echo "$error_message"
exit $return_code
fi
}
function get_s3_file {
local s3_path=$1
local local_path=$2
echo "Downloading $s3_path to $local_path..."
$(aws s3 cp $s3_path $local_path)
echo "$?"
}
if [[ ! -e "$FTP_PEM_FILE" ]]; then
exit_on_error $(get_s3_file $S3_PEM_PATH "/tmp/") "Failed to retrieve pem file "
fi
Running the above gives the following debug output:
+ exit_on_error 'Failed to retrieve pem file '
+ local 'return_code=Failed to retrieve pem file '
How can I return only the value of $? after running an external command, to the caller?
set -xto the very top of the script and see where it actually hangs. If you aren't sure this is where it hangs then you shouldn't have cropped the rest of the script.set -xvright before thatsftpline, andset +xvright after it. What prints out? Have you tried piping a command tosftpbefore?return $?but that's what functions do by default anyway, so you could leave it out entirely.