1

I have functions in my bash file:

function fn1 {
  echo "fn1 commands"
}

function fn2 {
  echo "fn2 commands"
}

function fn3 {
  echo "fn3 commands"
}

and I have array of functions - the bash execute function in the array:

funcs_to_test=( fn1 fn2 fn3 )

for testP in "${funcs_to_test[@]}"
do
    $testP
done

One more thing I need to do is to execute a function or functions by the command line input:

bash app.sh -f fn1 fn2

So I read the input like this:

while [[ "$#" -gt 0 ]]; do case $1 in
  -f|--fn) fns="$2"; shift;;
  *) echo "Unknown parameter passed: $1"; exit 1;;
esac; shift; done

and I want to set the value of fns to funcs_to_test if not empty:

if [ -z "$fns" ] then
  funcs_to_test=($fns)
fi

but I get an error:

syntax error near unexpected token `fi'

How to make execute these functions from the command line?

#!/bin/bash

function fn1 {
  echo "fn1 commands"
}

function fn2 {
  echo "fn2 commands"
}

function fn3 {
  echo "fn3 commands"
}
while [[ "$#" -gt 0 ]]; do case $1 in
  -f|--fsn) fns="$2"; shift;;
  *) echo "Unknown parameter passed: $1"; exit 1;;
esac; shift; done

funcs_to_test=( fn1 fn2 fn3 )

if [ -z "$fns" ] then
  funcs_to_test=($fns)      <--- here the problem. I do it wrong?
fi

for testP in "${funcs_to_test[@]}"
do
  $testP
done
0

2 Answers 2

3
if [ -z "$fns" ]; then
#               ^

Add a semicolon, or put the then on a separate line.

You can use ShellCheck to catch many such syntax errors.

Sign up to request clarification or add additional context in comments.

Comments

2

You may use this script that includes some syntax fixes and other suggested fixes:

function fn1 {
  echo "fn1 commands"
}

function fn2 {
  echo "fn2 commands"
}

function fn3 {
  echo "fn3 commands"
}

funcs_to_test=(fn1 fn2 fn3)

if (($# > 0)); then
   case $1 in
      -f|--fns) shift; funcs_to_test=("$@");;
      *) echo "Unknown parameter passed: $1"; exit 1;;
   esac;
fi

#declare -p funcs_to_test

for testP in "${funcs_to_test[@]}"; do
   printf '%s: ' 'executing'
   "$testP"
done

2 Comments

It would be good if you could explain the changes and fixes you've made.
Possibly add: IFS=$'\n' read -d '' -ra unk_funcs < <(LC_MESSAGES=C; declare -pF "${funcs_to_test[@]}" 2>&1 >/dev/null | cut -d ':' -f3); if [ "${#unk_funcs[@]}" -gt 0 ]; then { echo "Unknown functions:" ${unk_funcs[@]}; } 2>&1; fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.