Search code examples
bashls

Bash script for listing the files in a directory in a specific format witht the BASH shell


I am currently working on some C++ code on a GNU/Linux system and my source-code folder is filled with .cpp files and .h files.

In general for this code, every .cpp file has a corresponding .h header file, but not necessarily vice versa. In the output below -- indicates that there is no corresponding .cpp file for the listed header file

I would like to either write a bash script to do this by say defining an extra flag in my .bashrc / .zshrc , such that the listing of the files occurs in this format. Say I have 7 files, some .cpp and some .h

$ listscript
hello1.cpp hello1.h
hello2.cpp hello2.h
   --      hello3.h 
hello4.cpp hello4.h      

Solution

  • #!/usr/bin/env bash
    declare files=(*)
    declare file= left= right= width=10
    declare -A listed=()
    for file in "${files[@]}"; do
        if [[ $file == *.h ]]; then
            continue
        elif (( ${#file} > width )); then
            width=${#file}
        fi
    done
    for file in "${files[@]}"; do
        if [[ ${listed[$file]} == 1 ]]; then
            continue
        elif [[ $file == *.cpp ]]; then
            left=$file right=${file%.cpp}.h
        elif [[ $file == *.h ]]; then
            left=${file%.h}.cpp right=$file
        else
            left=$file right=
        fi
    
        [[ $left ]]     && listed["$left"]=1
        [[ $right ]]    && listed["$right"]=1
    
        [[ -e $left ]]  || left='--'
        [[ -e $right ]] || right='--'
    
        printf "%-*s %s\n" "$width" "$left" "$right"
    done