0

The situation:
I want to copy all odt files with size greater than 0 from one folder into another. Filenames will contain the following characters: + % & [ ( and spaces.

Here is my attempt:

#!/bin/bash

mvfunc ()
{
        if [ -s "$1" ]; then
                cp -n "$1" /home/telas/zztmp/currentfiles/
                /usr/bin/truncate -s 0 "$1"
                return 0
        fi
}

fileslist=$(ls --quoting-style=shell-always /home/telas/zzz/workingfiles/*.odt)

for filename in "$fileslist" ; do
        mvfunc "$filename"
done

All help is very much appreciated!!

  • can you provide the sample file names ? – Pacifist Mar 19 '16 at 12:08
  • 1
    Use for file in *.odt directly instead of parsing ls. – frostschutz Mar 19 '16 at 12:22
  • You need an array list. Something like odtList=(*.odt); for f in "${odtList[@]}"; do myfunc "$f"; done would be closer to your solution – Valentin Bajrami Mar 19 '16 at 12:24
2

You should rather use pathname expansion (globbing) in Bash than rely on external commands like ls.

If a for loop contains wildcards, then Bash uses globbing by default, so special characters won't mess like they would if interpreting the parameters given as a text string resulting from command substitution.

And the code will be cleaner and more portable, because --quoting-style= option is specific to GNU ls:

#!/bin/bash

mvfunc ()
{
        if [ -s "$1" ]; then
                cp -n "$1" currentfiles
                /usr/bin/truncate -s 0 "$1"
                return 0
        fi
}

for filename in /home/telas/zzz/workingfiles/*.odt; do
        mvfunc "$filename"
done
  • This won't work, because the file names might contain spaces. – TBrandt Mar 19 '16 at 14:44
  • @TBrandt And why exactly wouldn't it work? Did you test it? What was your result? – techraf Mar 19 '16 at 14:48
  • OK, my fault. When writing the glob directly after the "in" of the for loop, it seems to work (at least for bash and in cygwin). However, handling files and globs in Linux can be quite a problem, because filenames might contain wierd characters, such as space, tab, newline etc. Read dwheeler.com/essays/fixing-unix-linux-filenames.html for an in-depth discussion about many of these problems. – TBrandt Mar 19 '16 at 15:58
  • 1
    @TBrandt If you're having problems with filenames containing special characters, it's because you're doing something that you shouldn't be doing, such as parsing the output of ls or using unquoted variable expansions. Read Why does my shell script choke on whitespace or other special characters? – Gilles Mar 19 '16 at 16:01
  • I know all that but maybe I was a little too cautious. – TBrandt Mar 19 '16 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.