unpack 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/bin/bash
  2. # source: https://gist.github.com/markusfisch/871266/d522bf6589197724d8fcccb2b6c6e2a93bb366fc
  3. ##
  4. # Unpack archive safely (means always in its own directory)
  5. #
  6. # @param 1 - name and path of archive to extract
  7. #
  8. unpack()
  9. {
  10. local ARCHIVE=$1
  11. local TMP=.unpack-$USER-$$
  12. local EXTRACT=`basename "$ARCHIVE" | cut -d '.' -f 1`
  13. [ -f "$ARCHIVE" ] || {
  14. echo "$ARCHIVE not found"
  15. return 1
  16. }
  17. # ensure extracted directory is not yet there
  18. {
  19. local BASE="$EXTRACT"
  20. local N=2
  21. while [ -d "$EXTRACT" ]; do
  22. EXTRACT="$BASE-$N"
  23. (( N++ ))
  24. done
  25. }
  26. mkdir $TMP || {
  27. echo "cannot create temporary directory"
  28. return 1
  29. }
  30. cd $TMP || {
  31. echo "cannot change into temporary directory"
  32. return 1
  33. }
  34. case "$ARCHIVE" in
  35. *.zip)
  36. unzip "../$ARCHIVE"
  37. ;;
  38. *.rar)
  39. unrar x "../$ARCHIVE"
  40. ;;
  41. *.tbz2|*.tar.bz2)
  42. tar xjvf "../$ARCHIVE"
  43. ;;
  44. *.tgz|*.tar.gz)
  45. tar xzvf "../$ARCHIVE"
  46. ;;
  47. *.lz)
  48. tar xvf "../$ARCHIVE"
  49. ;;
  50. *.gz)
  51. gzip -d "../$ARCHIVE"
  52. ;;
  53. *.bzip2|*.bz2)
  54. bzip2 -d "../$ARCHIVE"
  55. ;;
  56. esac
  57. # move into place
  58. {
  59. local FILES=0
  60. for FILE in *
  61. do
  62. (( FILES++ ))
  63. done
  64. cd ..
  65. if (( FILES == 1 )); then
  66. mv -i $TMP/* .
  67. mv -i $TMP/.[!.]* .
  68. rmdir $TMP
  69. else
  70. mv -i $TMP $EXTRACT
  71. fi
  72. }
  73. return 0
  74. }
  75. for ARCHIVE in $@
  76. do
  77. # milisarge fixed this for full path extract
  78. cd `dirname $ARCHIVE`
  79. unpack "`basename $ARCHIVE`" || exit 1
  80. done