-1

Any idea what is wrong with this script? I am trying to check to see if the username is part of the present working directory file path. I have included two different implementations of the same thing, and neither of them work.

#!/bin/bash

USER_NAME=$(whoami)

if [[ "$USER_NAME" == *"$PWD"* ]]; then
  echo $PWD
else
  echo "not found"
fi

case "$USER_NAME" in 
  *$PWD*) echo $PWD ;;
esac

Also, this does not work either:

grep "$USER_NAME" "$PWD"

However, this works:

echo "$PWD" | grep "$USER_NAME"

Any idea what is going on here?

EDIT: This does not work either:

if [[ *"$PWD"* == "$USER_NAME" ]]; then
  echo "found"
else
  echo "not found"
fi

or even this:

if [[ $PWD == $USER_NAME ]]; then
  echo "found"
else
  echo "not found"
fi

or any other combination of * or quotes that I have tried so far.

EDIT2:

finally got it, have to use this:

if [[ $PWD == *$USER_NAME* ]]; then
  echo "found"
else
  echo "not found"
fi
user5359531
  • 3,217
  • 6
  • 30
  • 55

1 Answers1

1

There are two things, what you search for, and what you search in. You're mixing the two in your examples.

if [[ "$USER_NAME" == *"$PWD"* ]]; then
           ^------swap----^

And this greps in the file named by the contents of PWD clearly won't work, because PWD is a directory, not a file:

grep "$USER_NAME" "$PWD"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176