Search code examples
bashshellvalidationdebuggingdirectory

In Bash, how to define a list of directories and iterate through them?


#!/usr/bin/env bash

declare -a DIR=("/Volumes/drive1", "/Volumes/drive2", "~/temp", "~/file1")

[ -d "/Volumes/drive1" ] && echo "[DEBUG] 1"

#set -x ## DEBUG

for d in "${DIR[@]}"; do
    [ -d "${d}" ] && echo "[DEBUG] 2 ${d}"
done

When I run the script, it prints 1 but not 2.

I've looked up on the Web for tutorials on directory validation and iterating through list of files and directories but still could not figure out what's wrong with my code. Any idea what is wrong?


Solution

  • You need your tildes (~) to be unquoted:

    #!/usr/bin/env bash
    
    declare -a DIR=( "/Volumes/drive1" "/Volumes/drive2" ~/"temp" ~/"file1" )
    
    [[ -d /Volumes/drive1 ]] && echo "[DEBUG] 1"
    
    for d in "${DIR[@]}"; do
        [[ -d $d ]] && echo "[DEBUG] 2 ${d}"
    done
    

    There's no commas between items in an array in bash.


    declare -a DIR=( "/Volumes/drive1" "/Volumes/drive2" ~/"temp" ~/"file1" )
    

    can be written just:

    DIR=( /Volumes/drive1 /Volumes/drive2 ~/temp ~/file1 )
    

    Always first test your script to https://shellcheck.net before asking here.


    [[ is a bash keyword similar to (but more powerful than) the [ command. See http://mywiki.wooledge.org/BashFAQ/031 and http://mywiki.wooledge.org/BashGuide/TestsAndConditionals. Unless you're writing for POSIX sh, I recommend [[