check the directory exist

I have the below script to check whether directory is exist or not , now I sure the directory /abc NOT exist , but when run the script , it still pop the result is "the directory exist" , could suggest what is wrong ? thx

ll -d /abc > /dev/null 2>&1
if [ $? = 0 ]
then
echo "the directory exist !!"

else
echo "the directory not exist !!"
fi

You can directly do it with if

if [ -d abc ]
then
echo Directory found
else
echo Directory not found
fi

thx , I know your script is simpler and good, but I also want to know why my script has problem , can point out what is wrong ? thx

You need to change the line in red to

if [ $? -eq 0 ]

Even more concise (in ksh)

( [[ -d "/this/dir" ]] && echo "The directory exists" ) || echo "Does not exist"

Cheers
ZB

FYI ust:

if [ -d $dir ]
then
...
fi

is actually using the 'test' command. To find out what you can do with the test command then type: 'man test'

You may also write the above as:

if test -d $dir
then
...
fi

or even use the test command on the comand line thus:

>test -d $dir
>echo $?

Also I would recommend shell variables to be quoted in this context:

if [ -d "$dir" ] ...

to avoid any command line errors with the test command!

i.e. if $dir were emtpy and you did if [ -d $dir ], then you would really be running: 'test -d' and the test command would complain.

Hope this helps.

MBB

Hello:

Can someone please help me figure out what is wrong here, my script does not move on to the "else" part even though there is no .ssh directory on my remote server:

$more putkey.sh
#!/bin/ksh
for server in `cat list`
do
if [ -d /.ssh ]; then
cat $HOME/.ssh/id_rsa.pub |ssh $server ' cat >> .ssh/authorized_keys && echo "key copied"'
else
cat $HOME/.ssh/id_rsa.pub |ssh $server ' mkdir .ssh && cat >> .ssh/authorized_keys && echo "key copied"'
fi
done

$./putkey.sh
Password:
sh: .ssh/authorized_keys: cannot create

The script works if the else part is executed:

$cat $HOME/.ssh/id_rsa.pub |ssh myserver ' mkdir .ssh && cat >> .ssh/authorized_keys && echo "key copied"'
Password:
key copied

@Sara-sh your problem is not related to this thread , please start a new thread for your problem.