How to untar all .tar.gz with shell-script?

只谈情不闲聊 提交于 2019-12-03 16:25:25

问题


I tried this:

DIR=/path/tar/*.gz

if [ "$(ls -A $DIR 2> /dev/null)" == "" ]; then
  echo "not gz"
else
  tar -zxvf /path/tar/*.gz -C /path/tar
fi

If the folder has one tar, it works. If the folder has many tar, I get an error.

How can I do this?

I have an idea to run a loop to untar, but I don't know how to solve this problem


回答1:


for f in *.tar.gz
do
  tar zxvf "$f" -C /path/tar
done



回答2:


I find the find exec syntax very useful:

find . -name '*.tar.gz' -exec tar -xzvf {} \;

{} gets replaced with each file found and the line is executed.




回答3:


for a in /path/tar/*.gz
do
    tar -xzvf "$a" -C /path/tar
done

Notes

  • This presumes that files ending in .gz are gzipped tar files. Usually .tgz or .tar.gz is used to signify this, however tar will fail if something is not right.
  • You may find it easier to cd /path/tar first, then you can drop the -C /path/tar from the untar command, and the /path/tar/ in the loop.



回答4:


The accepted answer worked for me with a slight modification

for f in *.tar.gz
do
  tar zxvf "$f" -C \name_of_destination_folder_inside_current_path
done

I had to change the forward slash to a backslash and then it worked for me.



来源:https://stackoverflow.com/questions/4263156/how-to-untar-all-tar-gz-with-shell-script

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!