Stefan
Stefan

Reputation: 337

when to use double quotes in if-condition in shell scripts

I'm learning shell scripting for an exam and in our teachers book at one place he writes in an example the following:

# This script expects a folder path as an argument.
cd $1
if [ $? -ne 0 ]; then echo "Folder not found"; exit 1; fi

In another example however he writes:

# This script expects one argument
if [ "$#" -ne 1 ]; then echo "Missing Parameter"; exit 1; fi

Now, when do I have to put the tested argument within the square brackets in double quotes and when not?

I mean, $? in this case represents a number. However, $# in this example also represents a number and not a string (although everything is a string). But why is $# double-quoted and $? not?

Upvotes: 0

Views: 2920

Answers (2)

PrasannaK
PrasannaK

Reputation: 112

There is no difference, since Bash guarantees that both are numbers.

If there was a possibility that a variable might be a string, potentially with control characters or spaces, then it is necessary to quote.

Upvotes: 2

Raniendu Singh
Raniendu Singh

Reputation: 57

They mean the same thing. $values represent variables and will be used as variables inside and outside the quotes.

Upvotes: 0

Related Questions