Bash Functions Linux Shell Scripting Tutorial

Bash functions are mini scripts that exist within memory. So they can do more than one thing or create more complex commands. These environment functions are helpful when we might need to execute some operations repeatedly in a given shell session. Instead of typing the commands, again and again, we could place the commands in a function and then call the function. This article will not be an exhaustive guide on bash shell functions but instead, we’ll focus on creating quick functions on the Linux command line. The functions that we create at the shell prompt do not exist after we close the shell login session. Along with writing shell functions, we will also show you how to make these functions reusable across login sessions. Linux Shell Scripting Tutorial.

View Currently Available Bash Functions

To list the currently loaded environment functions, we use the declare -f command. This command shows the function names along with the function content.

Given below is a quick snippet from its output.

[root@Arkit-Serv ~]# declare -f | head
 __bh_bash_precmd ()
 {
 if [[ -e $BH_HOME_DIRECTORY/response.bh ]]; then
 local command=$(head -n 1 "$BH_HOME_DIRECTORY/response.bh");
 rm -i "$BH_HOME_DIRECTORY/response.bh";
 history -s "$command";
 __bh_preexec "$command";
 echo "$command";
 eval "$command";
 __bh_precmd;

Currently Available Shell Function Names

To only view the names of the environment functions and not the content, use the -F option with the declare command.

[root@Arkit-Serv ~]# declare -F | head
 declare -f __bh_bash_precmd
 declare -f __bh_check_bashhub_installation
 declare -f __bh_hook_bashhub
 declare -f __bh_path_add
 declare -f __bh_precmd
 declare -f __bh_precmd_run_script
 declare -f __bh_preexec
 declare -f __bh_process_command
 declare -f __bh_setup_bashhub
 declare -f __bh_trim_whitespace

View content of a particular function

You may use the declare command with the -f option followed by the environment function name to view the content of that function only. Given below is an example.

[root@Arkit-Serv ~]# declare -f __bh_bash_precmd
 __bh_bash_precmd ()
 {
 if [[ -e $BH_HOME_DIRECTORY/response.bh ]]; then
 local command=$(head -n 1 "$BH_HOME_DIRECTORY/response.bh");
 rm -i "$BH_HOME_DIRECTORY/response.bh";
 history -s "$command";
 __bh_preexec "$command";
 echo "$command";
 eval "$command";
 __bh_precmd;
 fi
 }

Create a Bash function

Thus far we’ve shown you how to list available functions. Now we will create our own function.

Create a function on the command line, use the function keyword followed by the desired function name and open a parenthesis. This will now take us to a PS2 prompt. Here we type in the body of the function. Once we are done typing, we put in a closed parenthesis to signify the end of the function. This will return us to our PS1 prompt and we may continue with our work while the function is ready for use.

In the below example, we create a function named info and add a couple of commands within the function body.

[root@Arkit-Serv ~]# function info {
 > uname -a
 > df -hTP
 > uptime
 > w
 > }

To use the info function we just created we simply need to type it on the command prompt and press enter.
Let’s give this a try.

[root@Arkit-Serv ~]# info
 Linux Arkit-Serv.com 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
 Filesystem Type Size Used Avail Use% Mounted on
 /dev/xvda1 xfs 20G 5.8G 15G 29% /
 devtmpfs devtmpfs 892M 0 892M 0% /dev
 11:20:19 up 13 min, 1 user, load average: 0.00, 0.07, 0.12
 11:20:19 up 13 min, 1 user, load average: 0.00, 0.07, 0.12
 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT
 user pts/0 122.248.16.5 11:08 3.00s 0.23s 0.20s sshd: user [priv]
 [root@Arkit-Serv ~]#

As you may observe, the commands we mentioned in the function were executed and we saw the output on the screen.

To view the content of this function, type declare -f info as shown below.

[root@Arkit-Serv ~]# declare -f info
 info ()
 {
 uname -a;
 df -hTP;
 uptime;
 w
 }

Create a Bash functions that takes an argument

In the previous example, we created a function, placed some commands in it and then tested it by calling the function on the command line. Now, we will create a function that takes an argument.

To demonstrate, I’ve created a function named clean_my_file. This function contains a sed command which will use $1as input. Here $1 is the first argument supplied to the function.

[root@Arkit-Serv ~]# function clean_my_file {
 > sed '/^\s*#/d;/^$/d' $1
 > }

The sed code simply deletes commented and blank lines from its input file.

Before using this function, let’s query that it’s accessible to the declare command.

[root@Arkit-Serv ~]# declare -F | grep clean
declare -f _git_clean
declare -f _yu_package_cleanup
declare -f clean_my_file
[root@Arkit-Serv ~]# declare -f clean_my_file
clean_my_file ()
{
sed ‘/^\s*#/d;/^$/d’ $1
}

Use this function on the fstab file, content is shown below.

[root@Arkit-Serv ~]# cat fstab

#
 # /etc/fstab
 # Created by anaconda on Mon Sep 29 21:48:54 2014
 #
 # Accessible filesystems, by reference, are maintained under '/dev/disk'
 # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
 #
 UUID=0f790447-ebef-4ca0-b229-d0aa1985d57f / xfs defaults 1 1
 /root/swap swap swap sw 0 0

We’ll now use the clean_my_file function on this file.

[root@Arkit-Serv ~]# clean_my_file fstab
 UUID=0f790447-ebef-4ca0-b229-d0aa1985d57f / xfs defaults 1 1
 /root/swap swap swap sw 0 0

From the above output, we can confirm that the function and the sed command worked as expected as the output did not contain any blank or commented lines.

Make a shell function persistent across login sessions

Functions we created thus far would be available only for the duration of the current login session. So if we were to log out and log back in we would lose the function and would have to write it again. To make sure that the functions we create persist across login sessions we may add them to our .bash_profile file as I’ve added the info function we created earlier in the .bash_profile profile for my user.

[root@Arkit-Serv ~]# cat .bash_profile
 # .bash_profile

# Get the aliases and functions
 if [ -f ~/.bashrc ]; then
 . ~/.bashrc
 fi# User specific environment and startup programs

PATH=$PATH:$HOME/bin

function info ()
 {
 uname -a;
 df -hTP;
 uptime;
 w
 }

Conclusion

This concludes our article on Bash functions where we demonstrated how to check available functions and create a function. Then demonstrated how to create a function that would take an argument and finally, we showed you how to ensure that the functions you create persist across login sessions. We hope that you’ve found this article interesting and it gives you some interesting ideas to implement shell functions to simplify some of your routine tasks.

Related Articles

11 Perl One Liner Script Examples

Real time CPULOAD Monitoring Script

Select Command to Create Menu Based Shell Scripts

Linux go More

Thanks for your wonderful Support and Encouragement

Sahil Suri

I am a system administrator who loves to learn and share my knowledge with the community. I've been working in the IT industry since 2011.

1 Response

  1. goutam says:

    Hi Sahil,

    None of the commands are working in RHEL 7. Can you let me know to use this functions

Leave a Reply

Your email address will not be published.