Search code examples
bashautomationdirectoryglob

bash create file in directory, only part of directory name is known


I have a bunch of directories named using the convention prefix.suffix. prefix is numeric and suffix is alphanumeric of any length.
mkdir 123.abcdef

prefix is always unique but I don't always know what suffix is at bash script runtime. Within my script, how can I have bash write to a given directory by knowing only the prefix?
The following doesn't work but I tried:
echo "itworks" > 123*/results.text


Solution

  • Glob the directory part to loop on the globs:

    shopt -s nullglob
    
    for dir in 123*/; do
        echo "itworks" > "${dir}results.text"
    done
    

    You can also enforce checking that there's a unique directory matching:

    shopt -s nullglob
    
    dirs=( 123*/ )
    if (( ${#dirs[@]} == 0 )); then
        echo >&2 "No dirs found!"
        exit 1
    elif (( ${#dirs[@]} > 1 )); then
        echo >&2 "More than one dir found!"
        exit 1
    fi
    
    # Here you're good
    echo "itworks" > "${dirs[0]}results.txt"