LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   What is wrong with this basic shell script? (https://www.linuxquestions.org/questions/linux-newbie-8/what-is-wrong-with-this-basic-shell-script-798534/)

Black.Sands 03-28-2010 10:43 PM

What is wrong with this basic shell script?
 
Hello LinuxQuestions world!

I'm still pretty new to linux, and burning through a unix/linux course offered at the local JC. I'm working on an assignment for shell scripting and I need to make a script that displays a bunch of junk (pwd, date, yadda yadda) and then prompts the user to enter a directory so they can view the contents. If it's valid, then it displays the contents. If it isn't then it throws an error message and the script stops. This is done using if, then and else.

The problem is, my script always shoots straight to the else, even if the subdir entered IS a valid subdirectory.

Here's what I have:

Code:

clear
pwd
echo Today is 'date +%m/%d/%y'
date +%r
echo "Which Subdirectory would you like to display?"
read subdir
if test -d $subdir
then
ls /cs41s1003/$subdir
else
echo "Sorry, $subdir is not a valid subdirectory! Give it another shot!"
fi

When I run the the script

Code:

./Assigment-3
I get:

Code:

/home/cs41s1003/Assignment-3
Today is date +%m/%d/%y
09:42:26 PM
Which Subdirectory would you like to display?
Assigment-3
Sorry, Assigment-3 is not a valid subdirectory! Give it another shot!
[cs41s1003@cc-ccs Assignment-3]$

Can anyone give me a heads up about what I'm fudging here?

Also, cs41s1003 is my "home" folder for the class on our linux server, which is a subdir of home. (home/cs41s1003/Assignment#/yadda/yadda)

Thanks!

Tristan

catkin 03-28-2010 10:51 PM

Please post the output of the script. It's easier to read if you put it in code tags (that's a link to instructions or you may prefer to use "Advanced Edit" mode which has a # button for code tags).

chrism01 03-29-2010 12:37 AM

Quote:

ls /cs41s1003/$subdir
dir does not exist; you want /home/cs41s1003/$subdir ; that's an absolute path ie parsed as starting from the system(!) root dir aka '/'
;)

grail 03-29-2010 03:13 AM

Also, your test is against the current directory structure so:

Quote:

if test -d $subdir
This is saying look in . (the directory you started in) for the directory you typed in.
So unless you have:

Quote:

/home/cs41s1003/Assignment-3/Assignment-3
Then it won't work either, ie the test will always be false.


All times are GMT -5. The time now is 04:41 PM.