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?
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.