Вопрос

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