1

I have this bash function which takes files as arguments:

txz()
{
  file_in=${@:1:$#-1}
  file_out=${@: -1}

  echo "file_in=${file_in}"
  echo "file_out=${file_out}"

  tar -cvf - ${file_in} | xz -e9zf - > "${file_out}"
}

The function should be invoked with at least 2 arguments. The last argument is always archive name, the rest of arguments are files to compress. The function works as it should when i invoke it for files without spaces in their names like:

txz File1 File2 archive.tar.xz

But it fails whith:

txz "File 1" "File 2" archive.tar.xz

file_in=File 1 File 2
file_out=archive.tar.xz
tar: File: Cannot stat: No such file or directory
tar: 1: Cannot stat: No such file or directory
tar: File: Cannot stat: No such file or directory
tar: 2: Cannot stat: No such file or directory
tar: Exiting with failure status due to previous errors

I also tried creating an array, but it doesn't work either:

txz()
{
  file_in=(${@:1:$#-1})
  file_out=${@: -1}

  echo "file_in=${file_in[@]}"
  echo "file_out=${file_out}"

  tar -cvf - "${file_in[@]}" | xz -e9zf - > "${file_out}"
}

How should i create the function so it works for all file names?

1 Answer 1

1

You should use BASH array to store multiple file names:

txz() { 
   file_in=( "${@:1:$#-1}" )
   file_out="${@: -1}"
   echo "file_in=${file_in[@]}"
   echo "file_out=${file_out}"

   tar -cvf - "${file_in[@]}" | xz -e9zf - > "${file_out}"
}

PS: Note how $@ must have double quoting in both assignments.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.