I am trying to make heads or tails of a shell script. Could someone please explain this line?
$FILEDIR is a directory containing files. F is a marker in an array of files that is returned from this command:
files=$( find $FILEDIR -type f | grep -v .rpmsave\$ | grep -v .swp\$ )
The confusing line is within a for loop.
for f in $files; do
target=${f:${#FILEDIR}}
<<do some more stuff>>
done
I’ve never seen the colon, and the hash before in a shell script for loop. I haven’t been able to find any documentation on them… could someone try and enlighten me? I’d appreciate it.
There are no arrays involved here. POSIX sh doesn’t have arrays (assuming you’re not using another shell based upon the tags).
The colon indicates a Bash/Ksh substring expansion. These are also not POSIX. The
#prefix expands to the number of characters in the parameter. I imagine they intended to chop off the directory part and assign it totarget.To explain the rest of that: first find is run and hilariously piped into two greps which do what could have been done with find alone (except breaking on possible filenames containing newlines), and the output saved into
files. This is also something that can’t really be done correctly if restricted only to POSIX tools, but there are better ways.Next,
filesis expanded unquoted and mutalated by the shell in more ridiculous ways for theforloop to iterate over the meaningless results. If the rest of the script is this bad, probably throw it out and start over. There’s no way that will do what’s expected.