How to catch an error in a linux bash script?

  • 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?

    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, that just tests if it's a directory, not if you can `cd` into it.

    @StephaneChazelas yes. The function name is `directoryExists`.

  • 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.)

    That also fixes (unless xpg_echo is on) the issues when filenames contain backslash characters.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM