How to create and use functions in Linux

Home > Search > How-to
  by

Piping the ls -l command through grep can be used to list directories.

[user1@server1 ~]# ls -l | grep "^d"
drwxr-xr-x  root  root  154635  Jan 01 00:01  directory1
drwxr-xr-x  root  root  154635  Jan 01 00:01  directory2
drwxr-xr-x  root  root  154635  Jan 01 00:01  directory3

 

A function can be created to do the same. For example, create a file named directories.sh that contains the following. In this example, the name of the function is xyz.

#!/bin/bash
xyz() { ls -l | grep "^d"; }

 

Prior to loading the function, the xyz command will produce an error, and set will not contain the xyz function.

[user1@server1 ~]# xyz
bash: xyz: command not found

[user1@server1 ~]# set | grep xyz

 

Load the directories.sh script using the source command.

[user1@server1 ~]# source directories.sh

 

Now the xyz command can be used.

[user1@server1 ~]# xyz
drwxr-xr-x  root  root  154635  Jan 01 00:01  directory1
drwxr-xr-x  root  root  154635  Jan 01 00:01  directory2
drwxr-xr-x  root  root  154635  Jan 01 00:01  directory3

 

Also, set will contain the xyz function.

[user1@server1 ~]# set | grep xyz
xyz ()

 

The unset command can be used to remove the function. For example, unset dir will remove the dir function.

[user1@server1 ~]# unset xyz

 

If you modify the directories.sh file, you will need to reload the directories.sh file using the source command again.

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments