I am trying to create a tar file of an existing file or directory (file_dir_name) in a specified directory (dir_path). I need the tar file to be named new_name.tar in the new directory. However, when I execute the below command, the tar file is saved in the directory I am currently in. Can anyone help me fix this?

tar -cvf "$new_name.tar" "$file_dir_name" -C "$dir_path"
  • 1
    Is -C $dir_path only there to try forcing the creation of the tarball in dir_path? If you are using GNU tar, it should be warning you that the -C option has no effect as the last argument. Are you trying to do the equivalent of tar cvf "$name.tar" "$file_or_dir" && mv "$name.tar" "$dir_path/" - where file_or_dir is an absolute path or a path relative to the current directory (not to dir_path)?
    – fra-san
    Oct 5, 2020 at 21:34

1 Answer 1


Specify the path to where you want the new tarball stored, e. g. tar cvf "${dir_path}"/new_name.tar "$file_dir_name" -C "$dir_path".

This presumes that the direcory corresponding with file_dir_name exists in dir_path.

  • will this work if the file does not exist in dir_path/ how would i make it work if it doesn't exist within the directory? Oct 5, 2020 at 17:16
  • If it does not exist it will probably throw an error. You can use test -d "${dir_path}/${file_dir_name}" to verify it exists as a pre-tarring sanity check.
    – DopeGhoti
    Oct 5, 2020 at 17:18
  • Do you know how I would modify your original answer so that it can accept relative or absolute paths? right now it only works for absolute Oct 5, 2020 at 17:34
  • Relative paths should work; the question is, relative to what? In this context, the paths are relative to $PWD in environment from which the command is run.
    – DopeGhoti
    Oct 5, 2020 at 17:45

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.