2

In Ubuntu 16.04 with Bash I created a file $HOME/ulcwe/software_internal.sh that contains a function rse() without a call. The file is sourced in ~/.bashrc (which was sourced by itself) and I can can call rse from anywhere in the terminal and it will run without error.

Yet I tried to run this script file that contains a call to rse in line 36, and I get this error:

line 36: rse: command not found

Why does the function called successfully in manual call (typing and executing rse in Bash) but not from the Bash script and how could I call it successfully from the script?

1 Answer 1

5

You will have to make sure that the function is available to the script. You can do this in two ways:

  1. source the file that contains the function definition, or
  2. export the function before calling the script (export -f rse would export the function).

Functions, just like shell variables, are not part of the environment that gets inherited by scripts. Shell variables has to be exported so that they become environment variables, and bash functions can likewise be exported.

Exported functions are not callable by any process, just by other bash scripts.

4
  • Thanks. I edited the question to clarify something I forgot to clarify: I sourced the file containing the function from bashrc and then sourced the relevant bashrc itself. I am surprised it still isn't enough to call the function from the aforementioned script-file (but enough for manual call from terminal). Commented Mar 4, 2018 at 13:07
  • 2
    Oh, I think I understand now, although the function-file is sourced from bashrc it isn't exported, hence not available for sub-processes like the script file I ran. Thus, I should export the function file and in bashrc, and not just source it there. Commented Mar 4, 2018 at 13:29
  • After the function definition, use export -f tdm (or export -f rse or whatever the function was called).
    – Kusalananda
    Commented Mar 4, 2018 at 13:37
  • 1
    Did that (in bashrc) then the function ran indeed from the script. Thanks. Commented Mar 4, 2018 at 14:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .