How to check if a variable is set in Bash?

(Usually) The right way where ${var+x} is a parameter expansion which evaluates to nothing if var is unset, and substitutes the string x otherwise. Quotes Digression Quotes can be omitted (so we can say ${var+x} instead of “${var+x}”) because this syntax & usage guarantees this will only expand to something that does not require quotes (since it either expands to x (which contains no word breaks so it … Read more

What does “-ne” mean in bash?

This is one of those things that can be difficult to search for if you don’t already know where to look. [ is actually a command, not part of the bash shell syntax as you might expect. It happens to be a Bash built-in command, so it’s documented in the Bash manual. There’s also an external … Read more

“unary operator expected” error in Bash if condition

If you know you’re always going to use Bash, it’s much easier to always use the double bracket conditional compound command [[ … ]], instead of the POSIX-compatible single bracket version [ … ]. Inside a [[ … ]] compound, word-splitting and pathname expansion are not applied to words, so you can rely on to compare the value of $aug1 with … Read more

How to mkdir only if a directory does not already exist?

Try mkdir -p: Note that this will also create any intermediate directories that don’t exist; for instance, will create directories foo, foo/bar, and foo/bar/baz if they don’t exist. Some implementation like GNU mkdir include mkdir –parents as a more readable alias, but this is not specified in POSIX/Single Unix Specification and not available on many common platforms like macOS, various BSDs, and various commercial … Read more