saving bash functions saving bash functions shell shell

saving bash functions


Your first statement is correct. A terminal instance runs a type of shell (bash, sh, csh)

You can add them to your ~/.bashrc file or add the saved script path (no compiling needed) to your PATH variable.

You could also just copy scripts to /usr/local/bin for quick access anytime. You would have no need to keep track of where they are relatively. This is quite handy and makes your scripts available to other users (or not if permissions are set correctly)


See the Using History Interactively section of the Bash Reference Manual for ways you can execute commands from your history.

For example, typing !?foo and pressing Enter will execute the most recent command containing "foo". I like to have shopt -s histverify histreedit in my ~/.bashrc so I can edit and confirm the command, if necessary rather than executing it immediately.

Also see the Commands For Manipulating The History section for keystrokes you can use to search for history entries to recall and execute.

For example, pressing Ctrl-r and typing foo will recall the most recent command containing "foo". You can press Ctrl-r additional times to continue searching in reverse for additional matching commands. Press Enter when you're ready to execute the one currently shown or Ctrl-g to abort the search.

If you add stty -ixon to your ~/.bashrc, then you can use Ctrl-s to search forward through history after you've begun searching backward.

Of course, you can save your functions by editing ~/.bashrc and adding them to it. I prefer to keep my functions in a file I created called ~/bin/functions and then add a line to ~/.bashrc to source that file. The line looks like . ~/bin/functions.

I save larger scripts in /usr/local/bin or ~/bin. The former should already be in your path and you can add the latter to your path by editing ~/.bashrc.


After you type in the functions on the command-line you could recall them using command-line editing (as @Dennis Williamson mentioned), but there is an easier method: declare -f. This command lists all current functions, and you can redirect them to a file:

home/user1> function myfunc {> echo "Hollow world!"> }/home/user1> declare -f > myfuncs/home/user1> more myfuncsmyfunc () {     echo "Hollow world"}

Note how Bash changes the function syntax from Korn shell to Bourne shell! Fortunately there is no difference between the two in Bash (unlike ksh93).

When you need to load the function it is a simple matter:

/home/user1> source myfuncs/home/user1> myfuncHollow world!

You don't need execute permissions by the way, only read.You could (as others have said) add this to one of your start-up files, like .bashrc.