The __function__ constant records the name of the current function in C + +. Sometimes it is useful to include this information in the log output. In bash, too, there is a constant funcname, but the difference is that it is an array, not a string, where the first element of the array is the name of the current function. Maybe it's a little hard to understand why funcname an array? Take a look at the example below and you'll see.
1#!/Bin/Bash2 3 functionTest_func ()4 {5echo " Current$FUNCNAME, \ $FUNCNAME=(${funcname[@]})"6 Another_func7echo " Current$FUNCNAME, \ $FUNCNAME=(${funcname[@]})"8 }9 Ten functionAnother_func () One { Aecho " Current$FUNCNAME, \ $FUNCNAME=(${funcname[@]})" - } - theecho "Out of function, \ $FUNCNAME=(${funcname[@]})" - Test_func -echo "Out of function, \ $FUNCNAME=(${funcname[@]})"
The result after execution is:
1Out of function, $FUNCNAME= ()2 CurrentTest_func, $FUNCNAME=(test_func Main)3 CurrentAnother_func, $FUNCNAME=(another_func test_func Main)4 CurrentTest_func, $FUNCNAME=(test_func Main)5Out of function, $FUNCNAME=()
Another useful constant similar to funcname is Bash_source, which is also an array, However, its first element is the name of the current script. It can be useful.
1 # if the script is sourced another script Span style= "color: #008080;" >2 if [ -N "$BASH _source"-a "$BASH _source"! = "$" then 4 do_something 5 else # Otherwise, run directly in 6 Do_other 7 fi
Bash_source[0] Bash_source[0] is equivalent to Bash_source, obtaining the path and file name of the currently executing shell file.
Create a new script test.sh under the directory/home/sam/linux programming exercise/shell:
1#!/Bin/Bash2DIR="$ (CD" $ (dirname "${bash_source[0]}" )/../"&&pwd) "3# DIR=$ (CD "$ (dirname ${bash_source[0]} )/../"&&pwd)4# DIR=' CD $ (dirname ${bash_source[0]} )/../ &&pwd '5 Echo $DIR6echo "OK"
Execution requires a EXECUTE permission: chmod +x test.sh then execute ./test.sh instead ofsh ./test.sh
Tested above write correct: output
1 /Home/Sam/Linux programming exercise 2 OK
is actually a: 1. Get the full path of the currently executing shell file 2. Executes the dirname and enters the parent directory 3. Process for printing the current working directory
1 # echo "${bash_source[ 0 " }" # echo "${bash_source}" 3 # echo " $ (dirname "${bash_source[ ] 4 # Dir= "$ (CD" $ (dirname ${bash_source[ 0 }) "&& pwd) " 5 # echo $DIR
With man bash, you can see the special usage of bash
1.${BASH_SOURCE-$0}
Get script Name
2. ${parameter:-default}
Slave_file=${hadoop_slaves:-${hadoop_conf_dir}/slaves} Specify Default value
3. ${parameter/pattern/string/}
${@// /\\ }
Linux in Bash_source[0]