Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing shell script function

Tags:

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?

like image 899
Reuben Avatar asked Dec 11 '12 05:12

Reuben


People also ask

How do you call a function in shell script?

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.

What does $() mean in shell script?

$() – the command substitution. ${} – the parameter substitution/variable expansion.

How do I import a file into a bash script?

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.


2 Answers

Yes, you can do like you mentioned above or like: . FILENAME

The file need not to end with .sh

like image 157
Sibi Avatar answered Sep 22 '22 18:09

Sibi


That's fine, here are some more hints:

  1. 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.

  2. You need read access only, and you do not need the #!/bin/bash (its just a comment).

  3. 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.

  4. Bash does not support the FPATH environment variable or autoload (as Korn shell does).

like image 44
cdarke Avatar answered Sep 19 '22 18:09

cdarke