I have a function err()
in file abc
. The files do not have a .sh
extension, but they start with #!/bin/bash
.
err () { echo "${1}" >&2 }
Now I am importing it in a different file xyz
:
source abc someFunction(){ err "Failed to back up" }
Is this the right way of importing?
When we call a function using the command ./myScript.sh function_name argument, the function_name becomes the first argument of the script. Therefore, we can check the “$1” variable in the case statement: “”) ;; – If the $1 argument is empty, it's a normal execution of the script instead of an external function call.
$() – the command substitution. ${} – the parameter substitution/variable expansion.
Show activity on this post. $ LANG=C help source source: source filename [arguments] Execute commands from a file in the current shell. Read and execute commands from FILENAME in the current shell. The entries in $PATH are used to find the directory containing FILENAME.
Yes, you can do like you mentioned above or like: . FILENAME
The file need not to end with .sh
That's fine, here are some more hints:
Use a naming convention for functions, for example prefix the function name with f_
, for example f_err
. Function calls appear no different as other commands, this is a hint to the reader. It also reduces the chances of a name collision.
You need read access only, and you do not need the #!/bin/bash
(its just a comment).
In Bash, some options have to be set before function parsing. For example, shopt -s extglob
has to be done before and outside the function if it uses extended globbing. Putting that inside the function is too late.
Bash does not support the FPATH environment variable or autoload (as Korn shell does).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With