Here's an essential procedure for declaring a permanent function:
Open ~/.bashrc
file in a text editor. Doesn't matter which text editor, so long as you know how to use it and so long as you open the /home/<username>/.bashrc
At the end of the ~/.bashrc
declare your own function, for instance:
find_dirs(){
find "$1" -type d
}
Save and close the file.
The ~/.bashrc
file is read every time you open interactive shell (that is new terminal tab, login via ssh
, or open TTY1 or other virtual console). This will not be available in script files, because ~/.bashrc
is not read for non-interactive shells. It is also not available if you run bash
with --norc
option.
If you want the function to be available immediately in the currently open tab, use source ~/.bashrc
command.
Functions take arguments just like regular commands. For example, $1
through $9
indicate the positional parameters when you call a function. In the example above find_dirs
takes one positional parameter only, and would be called as find_dirs /etc
. You can also use $@
to refer to all positional parameters. Functions also accept redirection. You can call a function with find_dirs $1 > /dev/null
; we also could declare it as follows:
find_dirs(){
find "$1" -type d
}
Note from man bash
: "Functions are executed in the context of the current shell; no new process is created to interpret them". That means that you also should be aware of functions having ability to alter your shell execution environment - change variables and terminal settings.