iUser iUser - 4 months ago 32
Bash Question

csh script - Get substring or remove last character from string

I'm trying to write a shell script. In that I'm getting path as location from user. I want to find out out if it ends with '/' or not. If it does, I have to remove it and assign it to another variable.

Script I tried

#!/bin/csh

set loc="/home/user/"
if (("$loc" == */ ))
then
echo true
set b=${loc::-1}
echo $b
else
echo false
endif


But I'm not getting any output.

Answer

try this;

#!/bin/csh
set loc="/home/user/"
set lastChar=`echo $loc | rev | cut -c -1`
if ( "$lastChar" == "/" ) then
    echo true
set b=`echo $loc | rev | cut -c 2- | rev`
#set b=`echo $loc | sed s'/.$//'`
#set b=`echo $loc | awk '{print substr($0, 1, length($0)-1)}'`
echo $b
else
    echo false
endif
Comments