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

Parsing JSON with Unix tools

There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq: You can also do this with tools that are likely already installed on your system, like Python using the json module, and so … Read more

Replace one substring for another string in shell script

To replace the first occurrence of a pattern with a given string, use ${parameter/pattern/string}: To replace all occurrences, use ${parameter//pattern/string}: (This is documented in the Bash Reference Manual, §3.5.3 “Shell Parameter Expansion”.) Note that this feature is not specified by POSIX — it’s a Bash extension — so not all Unix shells implement it. For the relevant POSIX documentation, see The Open Group Technical … Read more

What is the meaning of 2 in 2> /dev/null

The N> syntax in Bash means to redirect a file descriptor to somewhere else. 2 is the file descriptor of stderr, and this example redirects it to /dev/null. What this means in simple terms: ignore error output from the command. For example, if kill cannot stop a process because it doesn’t exist, or because the current user doesn’t have the permission to do … Read more

How can I declare and use Boolean variables in a shell script?

Revised Answer (Feb 12, 2014) Original Answer Caveats: https://stackoverflow.com/a/21210966/89391 From: Using boolean variables in Bash The reason the original answer is included here is because the comments before the revision on Feb 12, 2014 pertain only to the original answer, and many of the comments are wrong when associated with the revised answer. For example, Dennis Williamson’s … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)