2

I'm creating a backup function to copy all files with an specific extension extension.

files() returns '*' '+' './' when it has not found file results, so I'm trying to avoid the invalid cp [* | + | ./] /backup with an if but it only works for *.

function backupByExt {
  # $1 = extension $2 = searchPaths $3 = backPath
  ext=$1
  sp=$2
  bp=$3
  files=( "$sp" + *."$ext" )
  # printf 'Backing up %s files: %d\n' "$ext" "${#files[@]}"
  # loop over all the files having the current extension
  for f in "${files[@]}"
  do
    # printf 'File: %s bp: %s\n' "$f" "$bp"
    if [ "$f" != "*" ] && [ "$f" != "+" ] && [ "$f" != "./" ]; then
      cp "$f" "$bp"
    fi
  done
}
2
  • 2
    What's Python got to do with this - did you mean to tag it as bash ? Commented Mar 11, 2018 at 16:10
  • The "linux" tag isn't correct either, as should be obvious from its description. Commented Mar 11, 2018 at 21:36

2 Answers 2

2
files=( "$sp" + *."$ext" )

looks wrong; the + will become the second element of the arrey. You probably want

files=( "$sp"/*."$ext" )

The check for != * can be omitted by shopt -s nullglob.

A case statement might be more readable than your || chain (which should be &&):

case $f in
  ./|\+|\*)  ;;
  *) cp "$f" "$bp/" ;;
esac
Sign up to request clarification or add additional context in comments.

2 Comments

'shopt -s nullglob' is equivalent to '+nullglob'?
yes; you are right. -s is correct; + does not work
1

You need to use && (and).

This is because you only want to print the file if the results are not *, + or ./. This means that you want to make sure all three of those conditions are False, and the way you do this is by using &&.

Currently, your code isn't working as it first checks if results are not equal to *. If this condition is True, there is no need to evaluate the other two conditions so bash will just go to the next line of code (ignoring your other conditions as you're using or).

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.