Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I made the following script:

# !/bin/bash

# OUTPUT-COLORING
red='\e[0;31m'
green='\e[0;32m'
NC='\e[0m' # No Color

# FUNCTIONS
# directoryExists - Does the directory exist?
function directoryExists {
    cd $1
    if [ $? = 0 ]
            then
                    echo -e "${green}$1${NC}"
            else
                    echo -e "${red}$1${NC}"
    fi
}

# EXE
directoryExists "~/foobar"
directoryExists "/www/html/drupal"

The script works, but beside my echoes, there is also the output when

cd $1

fails on execution.

testscripts//test_labo3: line 11: cd: ~/foobar: No such file or directory

Is it possible to catch this?

share|improve this question
    
Just an FYI, you can also do this a lot simpler; test -d /path/to/directory ( or [[ -d /path/to/directory ]] in bash ) will tell you whether a given target is a directory or not, and it will do it quietly. –  Patrick Oct 22 '13 at 12:36
    
@Patrick, that just tests if it's a directory, not if you can cd into it. –  Stephane Chazelas Oct 22 '13 at 12:54
    
@StephaneChazelas yes. The function name is directoryExists. –  Patrick Oct 22 '13 at 13:57
add comment

4 Answers

up vote 2 down vote accepted

Your script changes directories as it runs, which means it won't work with a series of relative pathnames. You then commented later that you only wanted to check for directory existence, not the ability to use cd, so answers don't need to use cd at all. Revised. Using tput and colours from man terminfo:

#!/bin/bash -u
# OUTPUT-COLORING
red=$( tput setaf 1 )
green=$( tput setaf 2 )
NC=$( tput setaf 0 )      # or perhaps: tput sgr0

# FUNCTIONS
# directoryExists - Does the directory exist?
function directoryExists {
    # was: do the cd in a sub-shell so it doesn't change our own PWD
    # was: if errmsg=$( cd -- "$1" 2>&1 ) ; then
    if [ -d "$1" ] ; then
        # was: echo "${green}$1${NC}"
        printf "%s\n" "${green}$1${NC}"
    else
        # was: echo "${red}$1${NC}"
        printf "%s\n" "${red}$1${NC}"
        # was: optional: printf "%s\n" "${red}$1 -- $errmsg${NC}"
    fi
}

(Edited to use the more invulnerable printf instead of the problematic echo that might act on escape sequences in the text.)

share|improve this answer
    
That also fixes (unless xpg_echo is on) the issues when filenames contain backslash characters. –  Stephane Chazelas Oct 22 '13 at 14:28
add comment

Actually for your case I would say that the logic can be improved.

Instead of cd and then check if it exists, check if it exists then go into the directory.

if [ -d $1 ]
then
     echo -e "${green}$1${NC}"
     cd $1
else 
     echo -e "${red}$1${NC}"
fi  

But if your purpose is to silence the possible errors then cd $1 2>/dev/null, but this will make you debug in the future harder. You can check the if testing flags at: Bash if documentation:

share|improve this answer
    
This answer fails to quote the $1 variable and will fail if that variable contains blanks or other shell metacharacters. It also fails to check whether the user has permission to cd into it. –  IDAllen Oct 22 '13 at 13:38
    
I was actually trying to check if a certain directory existed, not necessarily cd to it. But because I didn't know better, I thought trying to cd to it would cause an error if not existed so why not catch it? I didn't know about the if [ -d $1 ] that's exactly what I needed. So, thank you a lot! (I'm used to proram Java, and checking for a directory in an if statement is not exactly common in Java) –  Thomas De Wilde Oct 22 '13 at 18:30
add comment

You don't say what exactly you mean by catch --- report and continue; abort further processing?

Since cd returns a non-zero status on failure, you could do:

cd -- "$1" && echo OK || echo NOT_OK

You could simply exit on failure:

cd -- "$1" || exit 1

Or, echo your own message and exit:

cd -- "$1" || { echo NOT_OK; exit 1; }

And/or suppress the error provided by cd on failure:

cd -- "$1" 2>/dev/null || exit 1

By standards, commands should put error messages on STDERR (file descriptor 2). Thus 2>/dev/null says redirect STDERR to the "bit-bucket" known by /dev/null.

(don't forget to quote your variables and mark the end of options for cd).

share|improve this answer
    
@Stephane Chazelas point of quoting and signaling end-of-options well taken. Thanks for editing. –  JRFerguson Oct 22 '13 at 13:36
add comment

Use set -e to set exit-on-error mode: if a simple command returns a nonzero status (indicating failure), the shell exits.

Beware that set -e doesn't always kick in. Commands in test positions are allowed to fail (e.g. if failing_command, failing_command || fallback). Commands in subshell only lead to executing the subshell, not the parent: set -e; (false); echo foo displays foo.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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