I'm trying to list all files in a sub-directory without their path, I just want the file name and extension, but Bash substitution doesn't work with all paths in an array, it only works with the first element.
Code:
#!/usr/bin/bash
NAME="$(pwd | grep -o '[^/]*$')"
# ls src -R
PATH="$(ls src/*.{cpp,hpp} 2> /dev/null)"
if [ 0 -eq "${#PATH[@]}" ]; then
echo "The project has no source code file yet."
exit 0
fi
EMPTY=''
for FILE in "${PATH[@]}"; do
echo "${FILE/src\//$EMPTY}"
done
Directory tree:
FileReader
├── bin
├── make.sh
├── obj
└── src
├── FileReader.cpp
├── FileReader.hpp
└── main.cpp
Expected:
$ bash make.sh
FileReader.cpp
FileReader.hpp
main.cpp
Output:
$ bash make.sh
FileReader.cpp
src/FileReader.hpp
src/main.cpp
( cd src ; ls *.{cpp,hpp} )dirname, also avoid using upper case variables in bash to avoid varname collision,PATHis already taken. AlsoPATHin your code is not an array.