I know this is basic, being a Bash beginner, I like to learn the level of checking and testing when calling commands like; cp, mkdir, wget,... in a Bash function, and returning a result for the function execution status.
For example, consider the following function.
# copy a file to a directory
# ${1} : full file path to be copied
# ${2} : directory file is copied to too
# return: 0, for successful copy function execution. 1, not copied. 2, function exception
function file_copy() {
local source="${1}"
local target="${2}"
local file_name
file_name=$(basename "${source}")
if cp --force "${source}" "${target}" &>/dev/null ;then
if [[ -f "${target}${file_name}" ]]; then
return 0
else
return 1 # copy not successful
fi
else
return 2 # function exception
fi
}
My questions for this case, is it possible for the cp
function not to error, but the copy didn't happen? Can I leave out the inner conditional, since the cp
function success implies the copy did indeed happen? Is it better not to have cp
as a conditional, and rather test for the target's existence?
Similarly, with wget
# download a package, tarball, appimage, ...
# ${1} : directory to download too, set to ~/Downloads
# ${2} : package, tarball, appimage, ... filename without directory
# ${3} : source url, repos
# return: 0, successful download. 1, otherwise
function package_download() {
local download_dir="${1:-${USER_DOWNLOAD}}"
local file_path="${download_dir}${2}"
local repos="${3}"
# --output-document = -O, --directory-prefix = -P
if wget --directory-prefix "${download_dir}" --output-document "${file_path}" "${repos}"; then
if [[ -f "${file_path}" ]]; then
return 0
else
return 1 # file didn't download
fi
else
return 1 # function exception
fi
}
Can wget
not error, yet the package didn't download? Am I over thinking things?
I know this is basic. Also, if the code looks a bit stringent, I'm using that ShellCheck extension for visual studio code.