How to call a function in shell Scripting?
Solution 1:
You don't specify which shell (there are many), so I am assuming Bourne Shell, that is I think your script starts with:
#!/bin/sh
Please remember to tag future questions with the shell type, as this will help the community answer your question.
You need to define your functions before you call them. Using ()
:
process_install()
{
echo "Performing process_install() commands, using arguments [${*}]..."
}
process_exit()
{
echo "Performing process_exit() commands, using arguments [${*}]..."
}
Then you can call your functions, just as if you were calling any command:
if [ "$choice" = "true" ]
then
process_install foo bar
elif [ "$choice" = "false" ]
then
process_exit baz qux
You may also wish to check for invalid choices at this juncture...
else
echo "Invalid choice [${choice}]..."
fi
See it run with three different values of ${choice}.
Good luck!
Solution 2:
#!/bin/bash
process_install()
{
commands...
commands...
}
process_exit()
{
commands...
commands...
}
if [ "$choice" = "true" ] then
process_install
else
process_exit
fi
Solution 3:
Example of using a function() in bash:
#!/bin/bash
# file.sh: a sample shell script to demonstrate the concept of Bash shell functions
# define usage function
usage(){
echo "Usage: $0 filename"
exit 1
}
# define is_file_exists function
# $f -> store argument passed to the script
is_file_exists(){
local f="$1"
[[ -f "$f" ]] && return 0 || return 1
}
# invoke usage
# call usage() function if filename not supplied
[[ $# -eq 0 ]] && usage
# Invoke is_file_exits
if ( is_file_exists "$1" )
then
echo "File found: $1"
else
echo "File not found: $1"
fi
Solution 4:
The functions need to be defined before being used. There is no mechanism is sh to pre-declare functions, but a common technique is to do something like:
main() { case "$choice" in true) process_install;; false) process_exit;; esac } process_install() { commands... commands... } process_exit() { commands... commands... } main()