Skip to content

Latest commit

 

History

History
121 lines (102 loc) · 1.7 KB

File metadata and controls

121 lines (102 loc) · 1.7 KB

Shell Function

Shell functions are “mini-scripts” that are located inside other scripts and can act as autonomous programs.

Shell functions have two syntactic forms:

function name {
	commands
	return
}

and

name () {
	commands
	return
}

For eg

#!/bin/bash

# Shell function

function func1 {
	echo "Step 2"
	return
}

echo "Step 1"
func1
echo "Step 3"

# Step 1
# Step 2
# Step 3

Global variables maintain their existence throughout the program. Inside shell functions, it is often desirable to have local variables.

#!/bin/bash
# local-vars: script to demonstrate local variables

# global variable foo
foo=0

funct_1 () {
	local foo
	foo=1
	echo "funct_1: foo = $foo"
}

funct_2 () {
	local foo
	foo=2
	echo "funct_2: foo = $foo"
}

echo "global: foo = $foo"
funct_1
echo "global: foo = $foo"
funct_2
echo "global: foo = $foo"

# global: foo = 0
# funct_1: foo = 1
# global: foo = 0
# funct_2: foo = 2
# global: foo = 0

Report with functions

#!/bin/bash
# Program to output a system information page
TITLE="System Information Report For $HOSTNAME"
CURRENT_TIME=$(date +"%x %r %Z")
TIMESTAMP="Generated $CURRENT_TIME, by $USER"

report_uptime () {
	cat <<- __EOF__
		<H2>System Uptime</H2>
		<PRE>$(uptime)</PRE>
	__EOF__
	return
}

report_disk_space () {
	cat <<- __EOF__
		<H2>Disk Space Utilization</H2>
		<PRE>$(df -h)</PRE>
	__EOF__
	return
}

report_home_space () {
	cat <<- __EOF__
		<H2>Home Space Utilization</H2>
		<PRE>$(du -sh /home/*)</PRE>
	__EOF__
	return
}

cat << _EOF_
	<HTML>
	<HEAD>
		<TITLE>$TITLE</TITLE>
	</HEAD>
	<BODY>
		<H1>$TITLE</H1>
		<P>$TIMESTAMP</P>
		$(report_uptime)
		$(report_disk_space)
		$(report_home_space)
	</BODY>
	</HTML>
_EOF_