-2

Write a shell script that asks a user for the absolute path to a directory, the script should test to see if the directory exists. If it does ls -l the directory. If not tell the user that the directory is not there. Save the file as list. I'm a beginner, but I cannot figure out how to get the script to print the ls -l after it confirms that the path is a directory.

#!/bin/bash
echo 'Please enter an absolute pathway'

read PATH

if ($PATH == -d)

then
echo  ls -l $PATH

else

echo "This is not a directory"

fi
  • 2
    Don't use PATH for one of your own variables: in fact it's best to avoid using all-caps variable names altogether (they should be reserved for 'system' variables) – steeldriver Mar 2 '16 at 23:29
  • An off-topic homework assignment. How far can we fall? – Marty Fried Mar 3 '16 at 0:16
  • 3
    Well, at least the user showed some effort - that's at least the main reason why I bothered answering this question. In addition , we're supposed to be a community , right ? Why not simply point the person who's just starting with scripting in the right direction (which is what I've done in my answer - no more no less ) ? – Sergiy Kolodyazhnyy Mar 3 '16 at 3:59
1

Your big issue is if ($PATH == -d) part. It should be

if [ -d "$FILEPATH"  ]

PATH is a special variable that is reserved. If you unset it, you cannot use whatever programs are stored in folders other than your current one. So , read man test about the options and proper syntax of the test [] command, and always quote variables

1

There are some problems with this script.

  • The variable PATH is already used by bash.
  • The test itself
  • The way to output the result

I would do it that way:

#!/bin/bash
read -p "Please enter an absolute pathway"
if test -d $REPLY
then
    ls -l $REPLY
else
    echo "This is not a directory"
fi
  • I would not do it that way if I were in the class. The teacher might want you to test it first, and I can see it won't work. However, I don't want to do someone's simple homework assignment. – Marty Fried Mar 3 '16 at 0:15
  • Somewhat redundant, you don't need to echo output of ls because it already prints to standard output. However, good alternative use of test and read prompt (saving up one line of echo). – Sergiy Kolodyazhnyy Mar 3 '16 at 3:57
  • @Serg You are right. Edited. – Jean-Marie Mar 4 '16 at 1:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.