Functions in Bash, Linux Shell Script.
2 min readMar 12, 2023
Syntax
function <name> or <name> ()
Create a function with custom name.
Return <value>
Return value as the return status as you exit the function.
Command <command>
Instead of using the function with the identical name, execute the same command.
Linux shell prompt create functions, unset and declare:
ubuntu:~/Bash_scripts# function f1 { echo "First function"; }
ubuntu:~/Bash_scripts# f2 () { echo "Second function"; }
ubuntu:~/Bash_scripts# f1;f2
First function
Second function
ubuntu:~/Bash_scripts# _user_input () { echo Hello $1;}
ubuntu:~/Bash_scripts# _user_input User
Hello User
ubuntu:~/Bash_scripts# declare -f f1 f2
f1 ()
{
echo "First function"
}
f2 ()
{
echo "Second function"
}
ubuntu:~/Bash_scripts# unset -f f1
ubuntu:~/Bash_scripts# declare -F
declare -f _user_input
declare -f f2
Function for user info script:
ubuntu:~$ vim get_user.sh
1 user_info () {
2 echo Current user: $USER
3 echo User UID: $UID
4 echo Home: $HOME
5 }
6
7 user_info
ubuntu:~$ bash get_user.sh
Current user: chsnv
User UID: 1000
Home: /home/chsnv
Simple function passing arguments:
ubuntu:~/Bash_scripts# vim create_files.sh
1 #!/bin/bash
2 f3 () {
3 touch $*
4 echo "File(s) created: $*"
5 }
6 f3 $*
ubuntu:~/Bash_scripts# bash create_files.sh aa.txt bb.txt dd.txt
File(s) created: aa.txt bb.txt dd.txt
ubuntu:~/Bash_scripts# ls
aa.txt bb.txt dd.txt
Function call, passing arguments another example:
ubuntu:~/Bash_scripts# vim return_values.sh
1 #!/bin/bash
2 calc () {
3 res=$(($1$2$3))
4 echo $res #return $res
5 }
6 n=$(calc $*) #n=$(calc $1 $2 $3)
7 echo $n
ubuntu:~/Bash_scripts# bash return_values.sh 3*6
18
ubuntu:~/Bash_scripts# bash return_values.sh 3/6
0
ubuntu:~/Bash_scripts# bash return_values.sh 3+6
9
ubuntu:~/Bash_scripts# bash return_values.sh 3–6
-3
Conclusion
A Bash function is a piece of reusable code created to carry out a certain task. The function can be used more than once in a script after it has been declared.