I would like to check the existence of directory and write the script below, but this doesn't work properly.

#!/bin/sh
if [ -d "~/sample" ]
then
    echo 'exists'
else
    echo 'NOT exists'
fi

Scripts below can work.

#!/bin/sh
if [ -d "/home/user01/sample" ]
then
    echo 'exists'
else
    echo 'NOT exists'
fi

if [ -d "~/sample" ] is something wrong?

有帮助吗?

解决方案

Yes the double quotes are what is not letting the ~ expand... the following will work:

if [ -d ~"/sample" ]; then
   echo "exists"
fi

It is usually better to use:

if [ -d "$HOME/sample" ] ; then
   echo "exists"
fi

$HOME is typically set by Bourne shells

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top