I am passing arguments to bash function, composed of directories and files. The following code validates the arguments before staring then in the array fdir
.
declare -A tag
for arg in "$@"; do
printf '%s\n' "arg: $arg"
[[ -d "$arg" || -f "$arg" ]] || continue
[[ ${tag[$arg]} ]] && continue
fdir+=("$arg")
tag[$arg]=1
done
Finally, I pass the contents of fdir
to the find command
and finally run head
on the matched files.
local _GREP="/bin/grep --color"
hn=13
sufx=( \( -name '*.sh' -o -name '*.c' \) )
mxdpt=( -maxdepth 3 )
find "${fdir[@]}" -type f "${sufx[@]}" "${mxdpt[@]}" \
-exec head -v -n "$hn" '{}' +
Because I use sufx
in the file command, if I pass a different type of file (e.g. /home/flora/file.org
), the find
will not find a match.
One solution would be to have directories to precede files in the array fdir
. Loop through each element in fdir
and set sufx=()
as soon as I detect the first file.
declare -A tag
local daggr=()
for arg in "$@"; do
[[ ! -d "$arg" ]] || continue
[[ ${tag[$arg]} ]] && continue
daggr+=("$arg")
tag[$arg]=1
done
local faggr=()
for arg in "$@"; do
[[ ! -f "$arg" ]] && continue
[[ ${tag[$arg]} ]] && continue
faggr+=("$arg")
tag[$arg]=1
done
fdir=( "${daggr[@]}" "${faggr[@]}" )
for (( i=0 ; i < $n ; i++ )); do
[[ -f "${fdir[$i]}" ]] && { sufx=() ; mxdpt=() ; }
find "${fdir[$i]}" -type f "${sufx[@]}" "${mxdpt[@]}" \
-exec head -v -n "$hn" '{}' +
done
Any advice on better or simpler ways that I could try?
*.sh
and*.c
. Please give an example tree structure.find
shall descend only into (sub)directories with these suffixes?*.sh
and*.c
are the file extensions. I want to be able to domyfunc /home/flora/lin /home/flora/mol/edv.f
.fdir
. Loop through each element infdir
and setsufx=()
as soon as I detect the first file.find
commands, one for directories and one for files. BTW, what versions of bash allowsufx=( ( -name *.sh -o -name *.c ) )
without quotes/escapes?-H
option offind
or change the[[ -f/-d file ]]
to[[ -f/-d file && ! -L file ]]