Articles

It will be good if you explain below part of code.

March 2, 2012 at 04:29:34
Specs: Windows 7

if [ $(echo $dir | grep \\.$ ) ]; then
dir=$(echo ${dir%/*})
fi
Can you please explain wat the above code is doing.

See More: It will be good if you explain below part of code.

Report •


#1
March 2, 2012 at 15:23:56

I think what the code is trying to do is check to see if $dir ends with \. If it does, then use ksh/bash pattern matching to show the directory's path: i.e.

/usr/nails/newbad/mydir\\.

becomes:

/usr/nails/newbad

Actually, the code you posted will not error out, but it will not do anything either - at least it does not work on my Solaris 9 box. Using [ or [[ in an if statement is a conditional requiring a 'var == value' context. One way is to use grep's -c option to find the number of times \\. happens. If it is greater than zero, determine the new $dir:

dir="/usr/nails/newbad/mydir\\."
if [[ $(echo $dir | grep -c \\.$) -gt 0 ]]
then
   dir=$(echo ${dir%/*})
   echo $dir
fi

Closer to what was originally posted, lose the [ and test the exist code of the grep command:

if echo $dir | grep \\.$ > /dev/null
then
   dir=$(echo ${dir%/*})
   echo $dir    # /usr/nails/newbad
fi

For more information, check out this link. Look for the Condtional Text Examples section:

http://www.dartmouth.edu/~rc/classe...


Report •
Related Solutions


Ask Question