0

I have a script, that tries to archive the contents of a directory with tar:

#!/bin/bash

find /root/files -type f -name "1*" -print0 | while read -d $'\0' file
do
    MYDIRNAME=$(dirname "${file}")
    MYFILENAME=$(basename "${file}")
    MYMODIFYDIR=$(echo "$MYDIRNAME" | sed 's/^\///' | sed 's/\//_/g' | sed 's/\ /_/g')
    MYMODIFYFILENAME=$(echo "$MYFILENAME" | sed 's/\//_/g' | sed 's/\ /_/g')
    GZIP=-9 tar -zcvf /root/"$MYMODIFYDIR"_"$MYMODIFYFILENAME".tar.gz "$file"
done

It does not work with files that have leading or trailing whitespace in their name. The error happens when reaching the file /root/files/tetst\ test\ tgdjd/1\ 5765765\ 565765\ (note the trailing whitespace in the filename):

tar: /root/files/tetst test tgdjd/1 5765765 565765: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

The error given by tar has the trailing whitespace trimmed from the filename.

bal
  • 159
  • 1
  • 8
Simon482
  • 137
  • 3
  • 8

2 Answers2

0

You can try this:

tar -zcvPf /root/"$MYMODIFYDIR"_"$MYMODIFYFILENAME".tar.gz "$file"

Use the -P option to disable this feature.

Eric.Chang
  • 71
  • 2
0

You forgot to reset IFS in the while loop, so the leading and trailing whitespaces gets treated as delimiter. Use this:

find /root/files -type f -name "1*" -print0 | while IFS= read -d $'\0' file

You could also add -r to read if there can be backslashes in the filenames.

See here for a more thourough explanation on read and IFS: https://stackoverflow.com/a/26480210/1262699

Community
  • 1
  • 1
bal
  • 159
  • 1
  • 8