ディレクトリの存在有無を確認

Contents

出力結果

Found: ./a_dir
Not Found: ./b_dir

前準備

プログラムと同じディレクトリにa_dirというディレクトリを作っておく

プログラム例

JavaScript

const fs = require('fs')
base_dir = __dirname
const exist_dir = base_dir + '/a_dir'
const not_exist_dir = base_dir + '/b_dir'
if(fs.existsSync(exist_dir)) { 
  console.log("Found: " + exist_dir)
}
if(!fs.existsSync(not_exist_dir)) { 
  console.log("Not Found: " + not_exist_dir)
}

Perl

use strict;
use File::Basename;
my $exit_dir = dirname(__FILE__).'/a_dir';
my $not_exist_dir = dirname(__FILE__).'/b_dir';
if(-d $exit_dir) {
  print "Found: ".$exit_dir."\n";
}
unless(-d $not_exist_dir) {
  print "Not Found: ".$not_exist_dir."\n";
}

PHP

<?php
$exist_dir = dirname(__FILE__).'/a_dir';
$not_exist_dir = dirname(__FILE__).'/b_dir';
if(file_exists($exist_dir) ) {
  print "Found: ".$exist_dir."\n";
}
if(!file_exists($not_exist_dir)) {
  print "Not Found: ".$not_exist_dir."\n";
}

Python

import os
base_dir = os.path.dirname(__file__)
if not base_dir:
  base_dir = "."
exit_dir = base_dir + '/a_dir'
not_exist_dir = base_dir + '/b_dir'
if(os.path.exists(exit_dir)):
  print("Found: " + exit_dir)
if(not os.path.exists(not_exist_dir)):
  print("Not Found: " + not_exist_dir)

Ruby

base_dir = File.dirname(__FILE__)
exit_dir = base_dir + '/a_dir'
not_exist_dir = base_dir + '/b_dir'
if(File.exist?(exit_dir)) 
  puts("Found: " + exit_dir)
end

if(!File.exist?(not_exist_dir)) 
  puts("Not Found: " + not_exist_dir);
end

Shell

base_dir=$(cd $(dirname $0); pwd);
exist_dir=$base_dir'/a_dir';
not_exist_dir=$base_dir'/b_dir';
if [ -d $exist_dir ]; then
  echo "Found: "$exist_dir;
fi
if [ ! -d $not_exist_dir ]; then
  echo "Not Found: "$not_exist_dir;
fi