20. Functions
#!/bin/bash
function print () {
echo $1 $2 $3
}
quit () {
exit
}
print Hello World Again
echo "foo"
quit
21. Local variables
#!/bin/bash
function print () {
local name=$1
# keyword local whether there is 'local' is different
echo "The name is $name"
}
name="Tom"
echo "The name is $name : Before"
print Max
echo "The name is $name : After"
# If there is no 'local' above , the variable 'name' is Max; Otherwise, it will be Tom.
echo "foo"
22. Function example
#!/bin/bash
usage(){
echo "You need to provide an argument : "
echo "usage : $0 file_name"
}
is_file_exist(){
local file="$1"
[[ -f "$file" ]] && return 0 || return 1
}
[[ $# -eq 0 ]] && usage
if ( is_file_exist "$1" )
then
echo "File found"
else
echo "File not found"
fi
23. Readonly command
#!/bin/bash
var=31
readonly var
var=50
echo "var => $var"
hello(){
echo "Hello World"
}
readonly -f hello
hello(){
echo "Hello World Again"
}
readonly -f #all functions are read only
readonly -p #all variables are read only
24. Signals and traps
#!/bin/bash
echo "pid is $$"
while ((COUNT < 10))
do
sleep 10
((COUNT ++))
echo $COUNT
done
exit 0
>> kill -9 jobname
#!/bin/bash
#trap "echo Exit signal is detected" SIGINT
#trap "echo Exit signal is detected" SIGKILL
file=/home/maq/work-miao/shelllearning/file1.txt
trap "rm -f $file && echo file deleted; exit" 0 2 15
echo "pid is $$"
while ((COUNT < 10))
do
sleep 10
((COUNT ++))
echo $COUNT
done
exit 0
25. How to debug a bash script
-
#!/bin/bash -x
-
>> bash -x hello.h
-
set -x #start to debug
-
set +x #end debugging
#!/bin/bash -x
#trap "echo Exit signal is detected" SIGINT
#trap "echo Exit signal is detected" SIGKILL
#set -x
file=/home/maq/work-miao/shelllearning/file1.txt
#set +x
trap "rm -f $file && echo file deleted; exit" 0 2 15
echo "pid is $$"
while ((COUNT < 10))
do
sleep 10
((COUNT ++))
echo $COUNT
done
exit 0
以上内容参考bilibili站视频https://www.bilibili.com/video/av51517726
/*今日标签*/
不介意孤独
比爱你更舒服