views:

190

answers:

3

I have a requirement in a shell script. I get this location information from a text file; it is always valid.

/opt/sasuapps/senny/publish/gbl/SANDHYA/drop1

I need to check if the directory is empty or not which I have done. If the directory is not empty, I need to delete the files and directory under that location.

As a part of security check, I would like to check if the drop location got from the file (/opt/sasuapps/senny/publish/gbl/SANDHYA/drop1) starts with any of the below.

/mnt/senny_publish/gbl
/mnt/senny/publish/gbl
/opt/sasuapps/senny/publish/gbl

If yes then only go ahead and delete; else don't do anything.

How can I compare the location given with those fixed strings?

+1  A: 

Assuming you are using bash for your shell script:

if [ -n "$(echo $LOCATION|grep -lE '/mnt/senny_publish/gbl|/mnt/senny/publish/gbl|/opt/sasuapps/senny/publish/gbl')" ]
then
    # Contains one of these paths
else
    # Does not contain one of these paths
fi

If you have a longer list of paths to look through, you could dump them to a tempfile, one per line, and use grep -lEf tempFileWithPaths.txt

nilbus
You probably also want to pass the `-q` option to grep to avoid printing extraneous junk to stdout
Adam Rosenfield
Technically, you've not enforced the 'starts with' condition; fixing that requires '^(...as before)'.
Jonathan Leffler
@Adam: he requires the output from -l to make the value non-empty. The standard output is captured and not echoed to the world.
Jonathan Leffler
@Jonathan: D'oh, you're right, I didn't read it very carefully.
Adam Rosenfield
A: 

use sed command

HKVN
+3  A: 

This will work in bash and any other Posix-style shell, i.e., it's OK for systems where /bin/sh is not bash.

check () {
  [ "x$1" = x ] && return 1
  for pf in /mnt/senny_publish/gbl              \
            /mnt/senny/publish/gbl              \
            /opt/sasuapps/senny/publish/gbl; do
      suf="${1#$pf}"
      [ x"$pf$suf" = x"$1" ] && return 0
  done
  return 1
}

testcheck () {
  echo -n "$1" :
  if check "$1"; then
      echo OK
  else
      echo BAD
  fi
}

testcheck /how/now
testcheck /not/this
testcheck /mnt/senny_publish/gbl
testcheck /mnt/senny/publish/gbl
testcheck /opt/sasuapps/senny/publish/gbl
testcheck /mnt/senny_publish/gbl/a/b
testcheck /mnt/senny/publish/gbl/a/b
testcheck /opt/sasuapps/senny/publish/gbl/a/b

So...

/how/now :BAD
/not/this :BAD
/mnt/senny_publish/gbl :OK
/mnt/senny/publish/gbl :OK
/opt/sasuapps/senny/publish/gbl :OK
/mnt/senny_publish/gbl/a/b :OK
/mnt/senny/publish/gbl/a/b :OK
/opt/sasuapps/senny/publish/gbl/a/b :OK

By avoiding grep and other external programs, we keep execution entirely in the shell, avoiding fork's and exec's, and which may also give additional protection against XSS attacks. Still, it would be a good idea to filter metachars early.

DigitalRoss
You forgot the output of your testcheck runs.
Dennis Williamson