[BASH] Best way to concat strings

There are many ways to concat strings in bash, but only one is the best. Let’s see the several methods:

x="debian"
y="linux"

z=$x$y		# does work		$z is "debianlinux"
z="$x$y"	# does work		$z is still "debianlinux"
z="$x9 $y"	# does not work		$z is just "linux"
z="${x}9 ${y}"	# does work (best)	$z is "debian9 linux"

So, in our opinion, the best way is the last one, always using the following syntax to get a variable value: ${VARIABLE}

[BASH] Get the source directory of a bash script

Often it’s very useful declaring a variable with the absolute path of the bash script. In doing so, you can prepend that variable to other sub-path variables (e.g., a sub-dir “logs”).

But, how can we dynamically get the source directory of a bash script? And why is that better than manually writing the static path? That’s better because of this simple reason: if you move the script or rename one of the parent directory where the script is within, you have to remember to update your code as well. Instead, using the following bash string, the absolute path is automatically updated:

$(dirname "${BASH_SOURCE[0]}")

Let’s see a common example where you can use the above code:

#!/bin/bash
TODAY=$(date +"%Y%m%d")
HOSTNAME=$(hostname)

ABSOLUTE_PATH=$(dirname "${BASH_SOURCE[0]}")
FILE_LOG="${ABSOLUTE_PATH}/logs/test.log"

echo "${TODAY} ${HOSTNAME}: Test QWERTY" >> ${FILE_LOG}

[BASH] Check if a file or dir exists

Run the following code to test a file and dir checking.

#!/bin/bash
FILE="/root/test.txt"
DIRECTORY="/sbin"

# IF FILE EXISTS
if [ -f $FILE ]; then
    echo "File $FILE exists."
fi


# IF FILE DOES NOT EXIST
if [ ! -f $FILE ]; then
    echo "File $FILE does not exist."
fi


# IF DIR EXISTS
if [ -d "$DIRECTORY" ]; then
    echo "Dir $DIRECTORY exists."
fi


# IF DIR DOES NOT EXIST
if [ ! -d "$DIRECTORY" ]; then
    echo "Dir $DIRECTORY does not exist."
fi