0

I am writing a very simple script which copies a file to a path provided by the user as a parameter and I would like to make sure the path starts with /var/log/messages.

So I've written this:

if [[ $2 -ne /var/log/messages/* ]]
then
  echo "Incorrect path, must be under /var/log/messages/"
  exit
fi

But it doesn't seem to work.

What am I doing wrong?

2
  • You can do [[ $2 != /var/log/messages/* ]] (incorrect path) Commented Apr 27, 2015 at 12:53
  • 2
    -ne is for arithmetic comparisons. Commented Apr 27, 2015 at 12:56

5 Answers 5

4

This should work:

if [[ "$2" != "/var/log/messages/"* ]]
then
  echo "Incorrect path, must be under /var/log/messages/"
  exit
fi
Sign up to request clarification or add additional context in comments.

Comments

2

You can use regular expressions as well (starting from Bash version 3). Just remember this:

Every quoted part of the regular expression is taken literally, even if it contains regular expression special characters.

In this case, you could do something like this:

if [[ ! "$2" =~ ^"/var/log/messages/" ]]
then
   echo "Incorrect path, must be under /var/log/messages/"
   exit
fi

Comments

1

You should in general provide a minimal non-working example. However, I suspect you want:

if [[ $2 != /var/log/messages/* ]]
then
  echo "Incorrect path, must be under /var/log/messages/"
  exit
fi

Comments

0

You could use dirname:

if [[ `dirname $2` != "/var/log/messages" ]]
then
  echo "Incorrect path, must be under /var/log/messages/"
  exit
fi

2 Comments

This doesn't account for subdirectories.
This is true, I thought he wanted to make sure that $2 was in /var/log/messages only
0

UNTESTED:

...
case $2 in
/var/log/messages/*) ;;
    # do whatever...
*)
    echo "incorrect ..."
    break
    ;;
esac
...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.