mardi 1 septembre 2020

Check if variable is set in Bash [duplicate]

I'm new to Bash programming and I'm quite confused about the conditional statements (compared to other programming languages). I want to check if one of my variables is set. I've found out, that Bash version 4.2+ supports a new conditional expression -v (more here, scroll down to -v) which can be used to check if a variable is set. If the variable is set, I also want to check if it contains valid path to which I can cd.

So I came up with this code:

function myFunc {
  if [[ -v myPathVar ]]; then
    if [[ -d $myPathVar ]]; then
      cd $myPathVar
      # do stuff here with a variable $1 which is passed into the function
    fi
  fi
}

But the code leads to this error for [[ -v myVar ]] and I don't know why:

conditional binary operator expected

When I change the code to single square brackets the if check works - which confuses me a lot.

So I got multiple questions here:

  1. Why does it not work with double square brackets? I read that those "new" double square brackets are "better". I also use them for file checks like if [[ -f $aFileVar ]]; then... which always worked.
  2. Do I need if statements when using double square brackets? I saw some examples where the if in front of the double square brackets was omitted and instead a && was added. Does this also work with a block of commands or only with a single command (or at least commands on the same line)?
  3. Can I directly use -d on a variable which may be not initialised? Or does it lead to a null pointer exception or something (like in Java)?

I would also appreciate to see how this small code example could actually be written.

Even if I have some experience with other programming languages I find it quite hard to get into Bash programming. For me, it seems like there are just those man style documentations which I find hard to search for specific information (unlike for example the Android developer documentation, which has a good search, pretty nice code examples and the technical explanations are imho well written).

Another point which confuses me is the way how Bash handles function parameters. From looking at the function declaration only I could not tell if there are parameters passed to the function or not, right? There is also no possibility to name the parameters or make sure, that the user has passed in all necessary parameters, right? So:

  1. I have no other choice than to check if the parameters I need for my function are properly set?

Aucun commentaire:

Enregistrer un commentaire