Categories
Linux Red Hat Ubuntu

Bash: remove trailing slash from a variable

Suppose you have a variable containing a directorypath:

#!/bin/bash
directorytouse="/home/myhome/whateverdirectory/"

If you try to test in your bash script if the directory exists, then it will fail because of the trailing slash:

if [ ! -d "${directorytouse} ] 
then
    echo -e "directory does not exist!"
fi

The easiest way to remove this / if it is present is to use shell parameter expansion:

if [ ! -d "${directorytouse%/}" ]
then
    echo -e "directory does not exist!"
fi

This will get rid of the trailing slash if there is one. If there is no trailing slash present, then nothing will happen.