Jared Allard
Jared Allard

Reputation: 933

'Globalize' Bash functions inside of a bash script

Alright, so let's say I have a .bash file with this inside of it

lib.bash

#!/bin/bash
function hello_world {
     echo "Hello World!"
}

That file won't be called on it's own, instead it'll be called via another bash file, i.e

Startup.bash

#!/bin/bash
bash lib.bash
hello_world

But, if I run Startup.bash I get the error: hello_world: command not found

What am I doing wrong, or is it not possible to do what I'm trying to do on bash.

Upvotes: 1

Views: 157

Answers (3)

konsolebox
konsolebox

Reputation: 75458

See if this could be helpful to you as well:

Shell Script Loader

Upvotes: 0

kiri
kiri

Reputation: 2632

You can use this command in your startup.bash:

source lib.bash

the source command runs the file in the current shell environment, unlike using bash lib.bash
(or . lib.bash) which creates a new, separate environment for that script (and only that script) and is why the function is not carried over.

(source)

Upvotes: 2

MPrazz
MPrazz

Reputation: 589

why don't you call the function directly inside of the first script?

It would look something like this:

#!/bin/bash
function hello_world {
     echo "Hello World!"
}
hello_world

If it is a simple script, shouldn't be a problem at all. Otherwise try the source command, like minerz029 suggested :)

Upvotes: 1

Related Questions