2

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

2
  • Are you aware that saying $(pwd) or $PWD would return you the directory from where you are executing the script and not the directory where the script is located? Commented Sep 18, 2013 at 7:10
  • Yeah. this example is just for practice. To see how I can return the output of a command in a variable and then do some conditional programming. Commented Sep 18, 2013 at 8:25

1 Answer 1

1

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 ]]
Sign up to request clarification or add additional context in comments.

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.