Functions can be defined at the command line or in a script. If they are defined at the command line they look like this:
dfh() { df -h ; }
Now until you exit the shell every time you use dfh you will get df -h results. Functions at the command line allow you to create temporary functions that are useful while the shell is open.
Here is a more complex example of functions at the command line. A bk function is defined within the brackets and then a second command is run to send an email to the root user.
bk() { tar cvf /bk/scripts.tar /root/scripts ; echo "Scripts Backed Up" | mail -s "Backup Status" root ; }
Now the bk function can be called as many times as needed and will work as long as you do not exit the shell.
The purpose of the function is to bind the name of the function to the list of commands that you create. This enables you to specify the name and all of the commands are executed.
function lsla { ls -la ; }
You can execute the list of commands by calling the name.
lsla
Examples:
Established connections to your server.
con () { netstat -aunt | grep -i established | sort; }
Sort folder size in the /home directory.
max () { du --max-depth=1 /home | sort -n -r; }
max
4060 /home
3976 /home/bill
64 /home/nagios
16 /home/snmptt
Sort folder size based on human readable options.
maxh () { du --si --max-depth=1 /home; }
maxh
17k /home/snmptt
66k /home/nagios
4.1M /home/bill
4.2M /home


{ 2 comments }
Wouldn’t it be more interesting if you also explained how to accept and pass parameters?
This is so cool! I learn every time I read one of these tutorials.
Comments on this entry are closed.