code_junkie

Determine if a function exists in bash

Nov 10th, 2011
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. fn_exists()
  2. {
  3. type $1 | grep -q 'shell function'
  4. }
  5.  
  6. batzel@batzel-laptop:~$ type foo
  7. bash: type: foo: not found
  8. batzel@batzel-laptop:~$ type ls
  9. ls is aliased to `ls --color=auto'
  10. batzel@batzel-laptop:~$ which type
  11. batzel@batzel-laptop:~$ type type
  12. type is a shell builtin
  13.  
  14. $ g() { return; }
  15. $ declare -f g > /dev/null; echo $?
  16. 0
  17. $ declare -f j > /dev/null; echo $?
  18. 1
  19.  
  20. test_declare () {
  21. a () { echo 'a' ;}
  22.  
  23. declare -f a > /dev/null
  24. }
  25.  
  26. test_type () {
  27. a () { echo 'a' ;}
  28. type a | grep -q 'is a function'
  29. }
  30.  
  31. echo 'declare'
  32. time for i in $(seq 1 1000); do test_declare; done
  33. echo 'type'
  34. time for i in $(seq 1 100); do test_type; done
  35.  
  36. real 0m0.064s
  37. user 0m0.040s
  38. sys 0m0.020s
  39. type
  40.  
  41. real 0m2.769s
  42. user 0m1.620s
  43. sys 0m1.130s
  44.  
  45. fn_exists()
  46. {
  47. type $1 2>/dev/null | grep -q 'is a function'
  48. }
  49.  
  50. fn_exists test_function
  51. if [ $? -eq 0 ]; then
  52. echo 'Function exists!'
  53. else
  54. echo 'Function does not exist...'
  55. fi
  56.  
  57. test_function () {
  58. ! type -f $1 >/dev/null 2>&1 && type -t $1 >/dev/null 2>&1
  59. }
Add Comment
Please, Sign In to add comment