SciIllustrator
SciIllustrator

Reputation: 1

Checking the last character of a filename in bash

I am trying to write a script that checks whether the user accidentally added an extra "/" to the end of a filepath (eg. MY_PATH) and if they did, it removes the last character. My script (see below) does successfully remove the last character of a path, but for some reason it also sometimes removes the last character even if it isn't "/". Does anyone know why it is doing this or how to fix it? I am open to alternative solutions.

MY_PATH="~/directory/Rscript.R"
#MY_PATH="~/directory/Rscript.R/"
if [ "${MY_PATH:$((${#MY_PATH}-1)):${#MY_PATH}}"=="/" ]
    then MY_PATH=${MY_PATH:0:$((${#MY_PATH}-1))}; fi
echo ${MY_PATH}

Upvotes: 0

Views: 887

Answers (3)

user1934428
user1934428

Reputation: 22366

The last character of a string is accessed by ${MY_PATH: -1}. You can test it as

if test ${MY_PATH: -1} = / ; then

or

if [ ${MY_PATH: -1} = / ]; then

or

if [[ ${MY_PATH: -1} = / ]]; then

or

if [[ ${MY_PATH: -1} == / ]]; then

or

if [[ ${MY_PATH: -1} =~ / ]]; then

The first three alternatives use string comparision, the 4th one wildcard matching, and the last one regex matching. Most of the spaces in those alternatives matter, so be sure that you get the spaces right.

Upvotes: 1

Jetchisel
Jetchisel

Reputation: 7831

You can try checking the last character by

if [[ ${MY_PATH:(-1)} = '/' ]]; then
  ...
fi

Upvotes: 0

Digvijay S
Digvijay S

Reputation: 2715

You can use sed

MY_PATH=$(sed 's#\/$##g' <<< ${MY_PATH})

Demo:

$MY_PATH="~/directory/Rscript.R/"
$MY_PATH=$(sed 's#\/$##g' <<< ${MY_PATH})
$echo $MY_PATH 
~/directory/Rscript.R
$MY_PATH="~/directory/Rscript.R"
$MY_PATH=$(sed 's#\/$##g' <<< ${MY_PATH})
$echo $MY_PATH 
~/directory/Rscript.R
$

Upvotes: 0

Related Questions