Vikram Chakrabarty
Vikram Chakrabarty

Reputation: 145

Bash scripting checking content of a variable containing a directory path

I am trying to write a simple bash script on Ubuntu 12.10 which stores the result of the pwd command in a variable and then checks the value of that variable in an if command to see if it matches a particular string. But I keep getting an error because it treats the content of that variable as a directory itself and keeps giving the error "No such file or directory"

The program is as below:

myvar=$(pwd)
if [$myvar -eq /home/vicky] #fails this check as variable myvar contains /home/vicky
then
    echo correct
else
    echo incorrect
fi

Any help would be appreciated

Upvotes: 2

Views: 270

Answers (1)

konsolebox
konsolebox

Reputation: 75458

The proper form for that is

myvar=$(pwd)
if [ "$myvar" = /home/vicky ]  ## Need spaces and use `=`.

And since you're in bash, you don't need to use pwd. Just use $PWD. And also, it's preferrable to use [[ ]] since variables are not just to word splitting and pathname expansion when in it.

myvar=$PWD
if [[ $myvar == /home/vicky ]]

Or simply

if [[ $PWD == /home/vicky ]]

Upvotes: 1

Related Questions