Bash function gives "command not found" when used within a bash script?

I have created a function aptget and sourced it:

$ type aptget
aptget is a function
aptget ()
{ sudo apt-get install -y $@
}

Here are the first few lines from the build.sh script:

#!/bin/bash
sudo apt remove -y x264 libx264-dev
#aptget build-essential checkinstall cmake pkg-config yasm
aptget git gfortran
aptget libjpeg8-dev libjasper-dev libpng12-dev
aptget libtiff5-dev
aptget libavcodec-dev libavformat-dev libswscale-dev libdc1394-22-dev
aptget libxine2-dev libv4l-dev

When attempting to use the aptget inside a bash script it is not found??

enter image description here

Maybe I'm missing something v simple here.. This is on ubuntu 18.04. Tips appreciated.

4

2 Answers

In general shell functions are not meant to be used outside of the shell they are defined in, so this answer is right. However in Bash you can do this:

export -f aptget

Then you call build.sh and it should know the function. This relies on the fact its interpreter is bash. In general other shells will not see the function. If you rewrite the script so it uses another interpreter, you will most likely lose the ability to call aptget from within the script.

Side general note: the name of your script is already misleading, it suggests the interpreter is sh. Suppose the script has grown and you decided it's time to rewrite it in python or whatever. You would like to do this without changing its name, because maybe other scripts use it (via the old name obviously). Therefore build.sh is not a good name; build may be.

The canonical way is to create a script named aptget and to place it in a directory where your PATH points to. The script should do what your function does. Some functions cannot be replaced by scripts (e.g. when they are meant to manipulate variables of the calling shell), but your particular function can. After you create a script, the function itself will not be needed.

Then aptget called from another script should just work.

Shell functions are not exported to subshells. If you want build.sh to have access to shell functions defined in your current shell instance, you must source it so it runs in your current instance. If you call it normally, a new shell instance will be spun up to run it, and that new subshell will not have access to the shell functions of your current shell instance.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like