How to Check whether a Directory or File Exists in Bash

Numerous scenarios will arise where you may need to perform an action based on whether a file exists or not.

While using the test command in Bash, you should determine whether a file exists and determine its file type.

A test command can take one of three possible syntax:

Test expression.

[ EXPRESSION ]

[[ EXPRESSION ]]

If you want a script to be portable, you should use the available command on all POSIX shells. The latest version of the test command, [[ (double brackets), is supported on most modern systems using the Bash, Zsh, and Ksh as a default shell.

Check if the file exists.

When checking a specific file, the most commonly used FILE operations include -e and -f. The first one will verify any file’s existence regardless of what type of file it is, while the second one will only return true for those files that are regular files (not a directory or a device).

The most efficient method of determining whether a file exists uses the test command and the if statement. Suppose you see any of the following, the /etc/resolv.conf file exists:

FILE=/etc/resolv.conf

if test -f "$FILE"; then

echo "$FILE exists."

fi
FILE=/etc/resolv.conf

if [ -f "$FILE" ]; then

echo "$FILE exists."

fi
FILE=/etc/resolv.conf

if [[ -f "$FILE" ]]; then

echo "$FILE exists."

fi

If you want to deliver a different action based on whether the file exists or not, simply use the if/then construct:

FILE=/etc/resolv.conf.

if [ "$FILE" ]; then

echo "$FILE exists."

else.

echo "$FILE does not exist."

fi

You can also operate a printer without the need for an if statement. The command following the && operator is only executed if the test command’s exit code is valid.

test -f /etc/resolv.conf && echo "$FILE exists."
[ -f /etc/resolv.conf ] && echo "$FILE exists."
[[ -f /etc/resolv.conf ]] && echo "$FILE exists."

When performing a series of commands using the && operator, make sure the semicolon does not separate them.

[ -f /etc/resolv.conf ] && { echo "$FILE exist."; cp "$FILE" /tmp/; }

What is said after the || operator is only valid as long as the test command’s exit status is false.

[ -f /etc/resolv.conf ] && echo "$FILE exist." || echo "$FILE does not exist."

Verify that Directory Exists.

The -d test tools you to quickly determine whether a file is a directory.

To check whether Docker’s /etc. The directory is present, use:

FILE=/etc/docker

if [ -d "$FILE" ]; then

echo "$FILE is a directory."

fi

[ -d /etc/docker ] && echo "$FILE is a directory."

Also, you can use the double brackets [[ instead of the single brackets [.

Check if the file already exists.

Moreover, the test expression can be negated using the word not. ! logical not operator:

FILE=/etc/docker

if not ( -f "$FILE" ]; then

echo "$FILE does not exist."

fi

Similar to above:

[ ! -f /etc/docker ] && echo "$FILE does not exist."

Check for multiple files.

Instead of using complex nested if/else statements, you can write a little more simply by using logic like this:

if [ -f /etc/resolv.conf -a -f /etc/hosts ]; then
echo "Both files exist."

fi

if [[ -f /etc/resolv.conf && -f /etc/hosts ]]; then

echo "Both files exist."

fi

Without using the IF statement:

[ -f /etc/resolv.conf -a -f /etc/hosts ] && echo "Both files exist."

[[ -f /etc/resolv.conf && -f /etc/hosts ]] && echo "Both files exist."

File test operators.

The test command includes some of the following file operators, which indicate whether a file is of a particular type.

  • -b FILE - True if that FILE exists and is also a special block file.
  • -c FILE - True if that FILE exists and is also a special character file.
  • -d source - True if source exists and is also a directory.
  • -e FILE - True if that FILE exists and is also a file, regardless of the type of (node, socket, directory, etc.).
  • -f FILE - True if that FILE exists and is also a regular file (not a device or directory).
  • -G FILE - True if that FILE exists and has the same group as the user is running that command.
  • -h FILE - True if that FILE exists and is also a symbolic link.
  • -g FILE - True if that FILE exists and also has set-group-id (sgid) flag set.
  • -k FILE – True if that FILE exists and also has a sticky bit flag set.
  • -L FILE – True if that FILE exists and is also a symbolic link.
  • -O FILE – True if that FILE exists and is also owned by the user running a command.
  • -p FILE – True if that FILE exists and is also a pipe.
  • -r FILE – True if that FILE exists and is also readable.
  • -S FILE – True if that FILE is also a socket.
  • -s FILE – True if that FILE exists and also has nonzero size.
  • -u FILE – True if that FILE exists, and also set-user-id (suid) flag is set.
  • -w FILE – True if that FILE exists and is also writable.
  • -x FILE – True if that FILE exists and is also executable.

Bash Concatenate Strings

Concatenation is one of the most popular and used string operations. String concatenation is just a decorative programming word for joining strings collectively by adding one string to another string’s end.

In this article, we will show how to concatenate strings in bash.

Concatenating Strings

The easiest way to concatenate two or more string variables is to write them one after another:

VAR1= "Hi,"
VAR2=" Lucky"
VAR3="$VAR1 $VAR2"
echo "$VAR3."

The last line will echo the concatenated string:

Output:
Hi, Lucky

With the help of a literal string, you can concatenate one or more variable:

VAR1= "Hey,"
VAR2= "${VAR1}World."
echo "$VAR2."
Output:
Hello, World

The example over variable VAR1 is enveloped in curly braces to guard the variable name against surrounding characters. When another valid variable-name character reflects the variable, you must have it in curly braces ${VAR1}.

To circumvent any word splitting or globbing issues, you should regularly try to use double quotes nearby the variable name if you want to suppress variable addition and special treatment of the backslash character rather than dual-use single quotes.

Bash does not separate variables by “type”; variables are used as integer or string depending on contexts. You can also combine variables that contain only digits.

VAR1 = "Hey, "
VAR2 = 2
VAR3 = " Lucky"
VAR4 = "$VAR1$VAR2$VAR3"
echo "$VAR4"
Output:
Hey, 2 Lucky

Concatenating Strings with the += operator

The other way of concatenating strings in bash is by combining variables or literal strings to a variable using the += Operator:

VAR1="Hey, "
VAR1+=" Lucky"
echo "$VAR1."
Output:
Hey, Lucky

The following sample is using the += operator to concatenate strings in bash for loop :

languages. sh
VAR= ""
for ELEMENT in 'Oxygen' 'Helium' 'Lime' 'Belly'; do
VAR+="${ELEMENT} "
done
echo "$VAR."
Output:
Oxygen Helium Lime Belly

Conclusion
Concatenating string variables is one of the most significant operations in Bash scripting. After reading this article, you should have a good knowledge of how to concatenate strings in bash. If you have any queries related to bash connect with us now.

How to Increment and Decrement Variable in Bash (Counter)

One of the most popular arithmetic operations when addressing Bash scripts is incrementing and decrementing variables. This is most regularly used in loops as a counter, but it can happen elsewhere in the script.

Incrementing and Decrementing center on adding or subtracting a value (usually 1), respectively, from the value of a numeric variable. The arithmetic augmentation can be performed using the double parentheses ((…)) and $((…)) or with the built-in let command.

In bash, there are various ways to increment/decrement a variable. In this article, some are explained.

Using + and – Operators

The easiest way to increment/decrement a variable is by using the + and – operators.

i=$((i+1))

((i=i+1))

let "i=i+1"
i=$((i-1))

((i=i-1))

let "i=i-1"

This method enables you to increment/decrement the variable by any value you want.

Here is an example of incrementing a variable within an until loop:

i=0

until [ $i -gt 3 ]

do

  echo i: $i

  ((i=i+1))

done

Output:

i: 0

i: 1

i: 2

i: 3

The += and -= Operators

In addition to the basic operators explained above, bash also provides the assignment operators += and -=. These operators are used to increment/decrement the left operand’s value with the value specified after the operator.

((i+=1))

let "i+=1"
((i-=1))

let "i-=1"

Copy

In the example below, we will show how to decrement the I variable’s value by 5.

i=20

while [ $i -ge 5 ]

do

  echo Number: $i

  let "i-=5" 

done

Output:

Number: 20

Number: 15

Number: 10

Number: 5

Using the ++ and — Operators

The ++ and — operators increment and decrement, respectively, its operand by 1 and return the value.

((i++))

((++i))

let "i++"

let "++i"
((i--))

((--i))

let "i--"

let "--i"

The operators can be used before or after the operand. They are also known as:

  • prefix increment: ++i
  • prefix decrement: –i
  • postfix increment: i++
  • postfix decrement: i–

The prefix operators first increment/decrement the operators by one and then return the new value to the operator. On the other hand, the postfix operators return the operators` value before incrementing/decremented the operator’s value.

If you only want to increment/decrement the variable, then there is no difference if you use the prefix or postfix operator. It only makes a difference if the operators’ result is accepted in some other operation or assigned to another variable.

The example below will show how the ++ operator works when is used before and after its operant:

x=5

y=$((x++))

echo x: $x

echo y: $y

Output

x: 6

y: 5
x=5

y=$((++x))

echo x: $x

echo y: $y
Copy

x: 6

y: 6

The example below shows us how to use the postfix incrementor in a bash script:

#!/bin/bash

i=0

while true; do

  if [[ "$i" -gt 3 ]]; then

    exit 1

  fi

  echo i: $i

  ((i++))

done

The downside of using these operators is that the variable can only be incremented or decremented by one only.

Conclusion                      

In bash, incrementing and decrementing variables can be performed in many different ways. So whatever method you use, the result is the same. If you have any query related to this, please write us.