1

i have probably some nooby question

how can I call a defined function in a if statement in bash?

Have a look on my example:

#!/bin/bash -x
Variable_A=xyz

function_x() {

echo "hello everyone"
}

#here I want to define a if statement after the function
if Variable_A == working;then
function_x()

#here I have a while for the parameters in bash example:
while [[ $# -gt 0 ]]
do
key="$1"
    case $key in
        -s|--status)
        Variable_A="$2"
        shift
        shift
        ;;
    esac
done

so the idea is when I run the script let's call it test.sh it runs the script exp in bash:

./test.sh working

I am not sure how to create something like this, maybe some of you can help me out on this.

Thank you in advance

Mladen Nikolic
  • 71
  • 1
  • 2
  • 8

1 Answers1

2

Your if should look like:

#here I want to define a if statement after the function
if [ "$Variable_A" = "working" ]
then
  function_x
fi

You need to end every if statement with fi and functions are called without ().
https://www.thegeekdiary.com/bash-if-loop-examples-if-then-fi-if-then-elif-fi-if-then-else-fi/

Another important note on if statements. You need a space before and after [ or ].

Your if logic should also be after the script parms are read and Variable_A is set.

GoinOff
  • 1,792
  • 1
  • 18
  • 37
  • Note that it should be `==` in the condition. –  Dec 05 '19 at 15:38
  • @vicraj who told you that? – oguz ismail Dec 05 '19 at 15:45
  • For checking string equality between variables, you should use `==`, and for integers, you should use `-eq`, as explained in this [Unix tutorial](https://www.tutorialspoint.com/unix/unix-basic-operators.htm). –  Dec 05 '19 at 15:49
  • @vicraj Actually I was told the right syntax is to use a single = just a few days ago here in SO, although both work. – Matias Barrios Dec 05 '19 at 15:51
  • OK, I didn't know. Since `==` is common to almost all programming languages, I prefer to continue using it anyway, since it is much more readable IMHO. –  Dec 05 '19 at 15:53
  • More thoroughly discussed [in this post](https://stackoverflow.com/questions/20449543/bash-equality-operators-eq) for those interested. –  Dec 05 '19 at 15:58
  • 3
    Single `=` is the portable one, see https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html – oguz ismail Dec 05 '19 at 16:05
  • 1
    @vicraj, ...if you want an example of a SO question / third-party bug caused by someone using the `==` (not-really-an-)operator instead of `=`, see https://stackoverflow.com/questions/3411048/unexpected-operator-in-shell-programming – Charles Duffy Dec 05 '19 at 16:12
  • @vicraj == is not "common to almost all programming languages". – linuxfan says Reinstate Monica Dec 05 '19 at 16:13
  • Ok, I get the point, thanks for the clarification. –  Dec 05 '19 at 16:22
  • 1
    thx, this worked :) awsome ! :) – Mladen Nikolic Dec 05 '19 at 16:33