-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathunpack.sh
More file actions
executable file
·927 lines (666 loc) · 25.5 KB
/
Copy pathunpack.sh
File metadata and controls
executable file
·927 lines (666 loc) · 25.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
#!/bin/bash
set -o errexit
set -o nounset
set -o pipefail
# set -x # Enable tracing of this script.
declare -r VERSION_NUMBER="1.23"
declare -r SCRIPT_NAME="${BASH_SOURCE[0]##*/}" # This script's filename only, without any path components.
declare -r -i BOOLEAN_TRUE=0
declare -r -i BOOLEAN_FALSE=1
declare -r -i EXIT_CODE_SUCCESS=0
declare -r -i EXIT_CODE_ERROR=1
abort ()
{
echo >&2 && echo "Error in script \"$SCRIPT_NAME\": $*" >&2
exit $EXIT_CODE_ERROR
}
add_to_str_list ()
{
local NEW_ELEMENT="$1"
local SEPARATOR="$2"
local MSG_VAR_NAME="$3"
local EVAL_CMD
if [[ ${!MSG_VAR_NAME} = "" ]]; then
printf -v EVAL_CMD \
"%s+=%q" \
"$MSG_VAR_NAME" \
"$NEW_ELEMENT"
else
printf -v EVAL_CMD \
"%s+=%q%q" \
"$MSG_VAR_NAME" \
"$SEPARATOR" \
"$NEW_ELEMENT"
fi
eval "$EVAL_CMD"
}
display_help ()
{
local SORTED_KEYS
readarray -t SORTED_KEYS < <( printf "%s\\n" "${!ALL_EXTENSIONS[@]}" | sort )
local KEY
local LINE_STR=""
local LINE_INDENTATION=" "
local LIST_SEPARATOR=" "
local SUPPORTED_EXTENSIONS=""
for KEY in "${SORTED_KEYS[@]}"; do
if (( ${#LINE_STR} + ${#LIST_SEPARATOR} + ${#KEY} > 80 )); then
SUPPORTED_EXTENSIONS+="$LINE_INDENTATION"
SUPPORTED_EXTENSIONS+="$LINE_STR"
SUPPORTED_EXTENSIONS+=$'\n'
LINE_STR=""
fi
add_to_str_list "$KEY" "$LIST_SEPARATOR" LINE_STR
done
if [ -n "$LINE_STR" ]; then
SUPPORTED_EXTENSIONS+="$LINE_INDENTATION"
SUPPORTED_EXTENSIONS+="$LINE_STR"
SUPPORTED_EXTENSIONS+=$'\n'
fi
# Remove the last newline character
SUPPORTED_EXTENSIONS="${SUPPORTED_EXTENSIONS::-1}"
cat - <<EOF
$SCRIPT_NAME version $VERSION_NUMBER
Copyright (c) 2019-2025 R. Diez - Licensed under the GNU AGPLv3
Overview:
This script unpacks an archive (zip, tarball, ISO image, etc.) into a subdirectory
inside the current directory (or the given destination directory), taking care that:
1) The destination directory does not get littered with many unpacked files.
2) No existing file or subdirectory is accidentaly overwritten.
3) The new file or subdirectory has a reasonable name, and that name
is displayed at the end.
Rationale:
There are many types of archives, an unpacking each type needs a different
tool with different command-line options. I can never remember them.
All archive types do have something in common: when unpacking,
you never know in advance whether you are going to litter the destination
directory with the extracted files, or whether everything is going into
a subdirectory, and what that subdirectory is going to be called.
Because of that, I have become accustomed to opening such files beforehand
with the current desktop's file manager and archiving tool. Some
file managers, like KDE's Dolphin, often have an "Extract here,
autodetect subfolder" option, but not all do, or maybe the right plug-in
for the file manager is not installed yet. Besides, if you are connected
to a remove server via SSH, you may not have a quick desktop
environment available.
So I felt it was time to write this little script to automate unpacking
in a safe and convenient manner.
This script creates a temporary subdirectory in the destination directory,
unpacks the archive there, and then it checks what files were unpacked.
Many archives in the form program-version-1.2.3.zip contain a subdirectory
called program-version-1.2.3/ with all other files inside it. This script
will then place that subdirectory program-version-1.2.3/
in the destination directory.
Other archives in the form archive.zip have contain many top-level files.
This script will then unpack those files into an archive/ subdirectory.
If the archive contains just one file, it will be placed in the destination directory.
In any case, if the desired destination file or directory already exists,
this script will not overwrite it. Instead, a temporary directory like
archive-unpacked-wtGQX will be left behind.
In the end, the user will be told where the unpacked archive contents are
and, where appropriate, that the normally-expected unpacked name already existed.
This script is designed for interactive usage and is not suitable
for automated tasks.
For convenience, it is recommended that you place this script
on your PATH. In this respect, see also GenerateLinks.sh in the same Git
repository this script lives in.
Alternative scripts that work in a similar fashion:
https://github.com/mitsuhiko/unp
https://github.com/githaff/unpack
Syntax:
$SCRIPT_NAME <options...> [--] <archive filename> [optional destination directory]
If the destination directory is not given, the current directory is used.
Options:
--help displays this help text
--version displays the tool's version number (currently $VERSION_NUMBER)
--license prints license information
Usage example:
$SCRIPT_NAME archive.zip
Supported filename extensions:
$SUPPORTED_EXTENSIONS
Exit status: 0 means success. Any other value means error.
Feedback: Please send feedback to rdiezmail-tools at yahoo.de
EOF
}
display_license ()
{
cat - <<EOF
Copyright (c) 2019-2023 R. Diez
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License version 3 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License version 3 for more details.
You should have received a copy of the GNU Affero General Public License version 3
along with this program. If not, see L<http://www.gnu.org/licenses/>.
EOF
}
process_command_line_argument ()
{
case "$OPTION_NAME" in
help)
display_help
exit $EXIT_CODE_SUCCESS
;;
version)
echo "$VERSION_NUMBER"
exit $EXIT_CODE_SUCCESS
;;
license)
display_license
exit $EXIT_CODE_SUCCESS
;;
*) # We should actually never land here, because parse_command_line_arguments() already checks if an option is known.
abort "Unknown command-line option \"--${OPTION_NAME}\".";;
esac
}
parse_command_line_arguments ()
{
# The way command-line arguments are parsed below was originally described on the following page:
# http://mywiki.wooledge.org/ComplexOptionParsing
# But over the years I have rewritten or amended most of the code myself.
if false; then
echo "USER_SHORT_OPTIONS_SPEC: $USER_SHORT_OPTIONS_SPEC"
echo "Contents of USER_LONG_OPTIONS_SPEC:"
for key in "${!USER_LONG_OPTIONS_SPEC[@]}"; do
printf -- "- %s=%s\\n" "$key" "${USER_LONG_OPTIONS_SPEC[$key]}"
done
fi
# The first colon (':') means "use silent error reporting".
# The "-:" means an option can start with '-', which helps parse long options which start with "--".
local MY_OPT_SPEC=":-:$USER_SHORT_OPTIONS_SPEC"
local OPTION_NAME
local OPT_ARG_COUNT
local OPTARG # This is a standard variable in Bash. Make it local just in case.
local OPTARG_AS_ARRAY
while getopts "$MY_OPT_SPEC" OPTION_NAME; do
case "$OPTION_NAME" in
-) # This case triggers for options beginning with a double hyphen ('--').
# If the user specified "--longOpt" , OPTARG is then "longOpt".
# If the user specified "--longOpt=xx", OPTARG is then "longOpt=xx".
if [[ "$OPTARG" =~ .*=.* ]] # With this --key=value format, only one argument is possible.
then
OPTION_NAME=${OPTARG/=*/}
OPTARG=${OPTARG#*=}
OPTARG_AS_ARRAY=("")
if ! test "${USER_LONG_OPTIONS_SPEC[$OPTION_NAME]+string_returned_if_exists}"; then
abort "Unknown command-line option \"--$OPTION_NAME\"."
fi
# Retrieve the number of arguments for this option.
OPT_ARG_COUNT=${USER_LONG_OPTIONS_SPEC[$OPTION_NAME]}
if (( OPT_ARG_COUNT != 1 )); then
abort "Command-line option \"--$OPTION_NAME\" does not take 1 argument."
fi
process_command_line_argument
else # With this format, multiple arguments are possible, like in "--key value1 value2".
OPTION_NAME="$OPTARG"
if ! test "${USER_LONG_OPTIONS_SPEC[$OPTION_NAME]+string_returned_if_exists}"; then
abort "Unknown command-line option \"--$OPTION_NAME\"."
fi
# Retrieve the number of arguments for this option.
OPT_ARG_COUNT=${USER_LONG_OPTIONS_SPEC[$OPTION_NAME]}
if (( OPT_ARG_COUNT == 0 )); then
OPTARG=""
OPTARG_AS_ARRAY=("")
process_command_line_argument
elif (( OPT_ARG_COUNT == 1 )); then
# If this is the last option, and its argument is missing, then OPTIND is out of bounds.
if (( OPTIND > $# )); then
abort "Option '--$OPTION_NAME' expects one argument, but it is missing."
fi
OPTARG="${!OPTIND}"
OPTARG_AS_ARRAY=("")
process_command_line_argument
else
OPTARG=""
# OPTARG_AS_ARRAY is not standard in Bash. I have introduced it to make it clear that
# arguments are passed as an array in this case. It also prevents many Shellcheck warnings.
OPTARG_AS_ARRAY=("${@:OPTIND:OPT_ARG_COUNT}")
if [ ${#OPTARG_AS_ARRAY[@]} -ne "$OPT_ARG_COUNT" ]; then
abort "Command-line option \"--$OPTION_NAME\" needs $OPT_ARG_COUNT arguments."
fi
process_command_line_argument
fi
# If the only command-line arguments are '--help', '--version' and '--license',
# then this code is unreachable, so disable the related ShellCheck warning.
# shellcheck disable=SC2317
((OPTIND+=OPT_ARG_COUNT))
fi
;;
*) # This processes only single-letter options.
# getopts knows all valid single-letter command-line options, see USER_SHORT_OPTIONS_SPEC above.
# If it encounters an unknown one, it returns an option name of '?'.
if [[ "$OPTION_NAME" = "?" ]]; then
abort "Unknown command-line option \"$OPTARG\"."
else
# Process a valid single-letter option.
OPTARG_AS_ARRAY=("")
process_command_line_argument
fi
;;
esac
done
shift $((OPTIND-1))
ARGS=("$@")
}
add_extension ()
{
local EXT="$1"
local FN="$2"
if test "${ALL_EXTENSIONS[$EXT]+string_returned_ifexists}"; then
abort "Internal error: Extension \"$EXT\" is duplicated."
fi
ALL_EXTENSIONS["$EXT"]="$FN"
}
str_ends_with ()
{
# $1 = string
# $2 = suffix
case "$1" in
*$2) return $BOOLEAN_TRUE;;
*) return $BOOLEAN_FALSE;;
esac
}
add_all_extensions ()
{
add_extension .tar unpack_tar
add_extension .tar.gz unpack_tar
add_extension .tgz unpack_tar
add_extension .tar.bz2 unpack_tar
add_extension .tb2 unpack_tar
add_extension .tbz unpack_tar
add_extension .tbz2 unpack_tar
add_extension .tar.lzma unpack_tar
add_extension .tlz unpack_tar
# tar needs tool 'lzip' to decompress .tar.lz files, but 'lzip' is often not installed by default.
# There is no short suffix for .tar.lz . Suffix .tlz is alreay taken by .tar.lzma .
add_extension .tar.lz unpack_tar
add_extension .tar.xz unpack_tar
add_extension .txz unpack_tar
add_extension .tar.Z unpack_tar
add_extension .tZ unpack_tar
add_extension .tar.zst unpack_tar
add_extension .tzst unpack_tar
add_extension .7z unpack_7z
add_extension .zip unpack_zip
# For ISO images, alternatively use:
# - isoinfo -i image.iso -R # But you get "CD-ROM is NOT in ISO 9660 format" for some ISO images in UDF or other formats.
# - bsdtar -xf image.iso # Not tested yet.
# We could try to extract the CD-ROM label inside (if any) and use it for the directory name.
add_extension .iso unpack_7z
# .gz files typically contain only one compressed file. The data structure could allow for several files,
# but most tools assume all compressed data chunks belong to a single file.
add_extension .gz unpack_gunzip
# .Z files are no archives, they only contain a single compressed file.
add_extension .Z unpack_uncompress
# .xz files are no archives, they only contain a single compressed file.
# Note that extension .tar.xz is handled separately above.
add_extension .xz unpack_xz
# .zst files contain a single compressed file. Even though the zstd documentation states that
# "It is possible to concatenate .zst files as is. zstd will decompress
# such files as if they were a single .zst file."
# all decompressed data goes to a single file, as .zst files do not store the original filenames.
# Note that extension .tar.zst is handled separately above.
add_extension .zst unpack_zstd
add_extension .deb unpack_deb
add_extension .rpm unpack_rpm
add_extension .rar unpack_rar
# .bz and .bz2 files are no archives, they only contain a single compressed file.
add_extension .bz unpack_bzip
add_extension .bz2 unpack_bzip
}
is_tool_installed ()
{
if command -v "$1" >/dev/null 2>&1 ; then
return $BOOLEAN_TRUE
else
return $BOOLEAN_FALSE
fi
}
abort_because_tool_not_installed ()
{
local TOOL_NAME="$1"
local DEBIAN_PACKAGE_NAME="$2"
local ERR_MSG="Tool '$TOOL_NAME' is not installed. You may have to install it with your Operating System's package manager."
if [[ $DEBIAN_PACKAGE_NAME != "" ]]; then
ERR_MSG+=" For example, under Ubuntu/Debian the corresponding package is called \"$DEBIAN_PACKAGE_NAME\"."
fi
abort "$ERR_MSG"
}
verify_tool_is_installed ()
{
local TOOL_NAME="$1"
local DEBIAN_PACKAGE_NAME="$2"
if ! is_tool_installed "$TOOL_NAME"; then
abort_because_tool_not_installed "$TOOL_NAME" "$DEBIAN_PACKAGE_NAME"
fi
}
unpack_tar ()
{
local TAR_TOOL="tar"
verify_tool_is_installed "$TAR_TOOL" "tar"
local CMD
printf -v CMD "%q --auto-compress --extract --force-local --file %q" "$TAR_TOOL" "$ARCHIVE_FILENAME_ABS"
echo "$CMD"
eval "$CMD"
}
unpack_zip ()
{
local ZIP_TOOL="unzip"
verify_tool_is_installed "$ZIP_TOOL" "unzip"
local CMD
printf -v CMD "%q -q -- %q" "$ZIP_TOOL" "$ARCHIVE_FILENAME_ABS"
echo "$CMD"
eval "$CMD"
}
unpack_7z ()
{
local SEVENZ_TOOL="7zz"
local SEVENZ_TOOL_OLD="7z"
local ISSUE_WARNING_ABOUT_SEVENZ_TOOL_OLD=false
if is_tool_installed "$SEVENZ_TOOL"; then
# Unfortunately, 7zz does not have a "quiet" or "silent" option.
# We could redirect all output to /dev/null, which is the same as specifying
# option -bso0, but then you would not see an eventual password prompt.
local CMD
printf -v CMD \
"%q x -- %q" \
"$SEVENZ_TOOL" \
"$ARCHIVE_FILENAME_ABS"
elif is_tool_installed "$SEVENZ_TOOL_OLD"; then
ISSUE_WARNING_ABOUT_SEVENZ_TOOL_OLD=true
# Unfortunately, 7z does not have a "quiet" or "silent" option.
# We could redirect all output to /dev/null, but then you would not
# see an eventual password prompt.
# Recent versions have options -bsp0 -bso0, but my current version is too old.
local CMD
printf -v CMD \
"%q x -- %q" \
"$SEVENZ_TOOL_OLD" \
"$ARCHIVE_FILENAME_ABS"
else
abort_because_tool_not_installed "$SEVENZ_TOOL" "7zip"
fi
echo "$CMD"
eval "$CMD"
if $ISSUE_WARNING_ABOUT_SEVENZ_TOOL_OLD; then
echo >&2
echo "WARNING: Tool 7z has not been maintained for years (as of August 2023) and is no longer recommended." >&2
fi
}
unpack_gunzip ()
{
local GUNZIP_TOOL="gunzip"
verify_tool_is_installed "$GUNZIP_TOOL" "gzip"
local CMD
printf -v CMD "%q --to-stdout -- %q >%q" \
"$GUNZIP_TOOL" \
"$ARCHIVE_FILENAME_ABS" \
"$ARCHIVE_NAME_ONLY_WITHOUT_EXT"
echo "$CMD"
eval "$CMD"
}
unpack_bzip ()
{
local BZIP_TOOL="bzip2"
verify_tool_is_installed "$BZIP_TOOL" "bzip2"
# If you do not use option '--stdout', then you probably want to use '--keep'.
# Faster alternatives: lbzip2, mpibzip2
local CMD
printf -v CMD "%q --decompress --stdout -- %q >%q" \
"$BZIP_TOOL" \
"$ARCHIVE_FILENAME_ABS" \
"$ARCHIVE_NAME_ONLY_WITHOUT_EXT"
echo "$CMD"
eval "$CMD"
}
unpack_uncompress ()
{
# Normally, the "uncompress" tool is actually a compatible alternative that comes with the gzip package.
# We could specify here "uncompress.real" to use the original version, at least on Ubuntu/Debian.
# I have actually tested with uncompress.real, and it does work.
local UNCOMPRESS_TOOL="uncompress"
verify_tool_is_installed "$UNCOMPRESS_TOOL" "gzip"
# The old 'uncompress' tool did not have a '--' separator between options and filename.
local CMD
printf -v CMD "%q -c %q >%q" \
"$UNCOMPRESS_TOOL" \
"$ARCHIVE_FILENAME_ABS" \
"$ARCHIVE_NAME_ONLY_WITHOUT_EXT"
echo "$CMD"
eval "$CMD"
}
unpack_xz ()
{
local UNCOMPRESS_TOOL="xz"
verify_tool_is_installed "$UNCOMPRESS_TOOL" "xz-utils"
# We would normally use flags "--decompress --keep", but the decompressed file
# would then land next to the compressed one, and not in the current directory.
local CMD
printf -v CMD "%q --decompress --to-stdout -- %q >%q" \
"$UNCOMPRESS_TOOL" \
"$ARCHIVE_FILENAME_ABS" \
"$ARCHIVE_NAME_ONLY_WITHOUT_EXT"
echo "$CMD"
eval "$CMD"
}
unpack_zstd ()
{
local UNCOMPRESS_TOOL="zstd"
verify_tool_is_installed "$UNCOMPRESS_TOOL" "zstd"
local CMD
printf -v CMD "%q --decompress --stdout -- %q >%q" \
"$UNCOMPRESS_TOOL" \
"$ARCHIVE_FILENAME_ABS" \
"$ARCHIVE_NAME_ONLY_WITHOUT_EXT"
echo "$CMD"
eval "$CMD"
}
unpack_deb ()
{
local UNCOMPRESS_TOOL="ar"
verify_tool_is_installed "$UNCOMPRESS_TOOL" "binutils"
local CMD
printf -v CMD "%q x -- %q" \
"$UNCOMPRESS_TOOL" \
"$ARCHIVE_FILENAME_ABS"
echo "$CMD"
eval "$CMD"
}
unpack_rpm ()
{
# Alternatively, we could use 7z/7zz, which can unpack .rpm files too.
# The result is a .cpio file, but you can unpack it with 7z/7zz too.
local UNCOMPRESS_TOOL="rpm2cpio"
verify_tool_is_installed "$UNCOMPRESS_TOOL" "rpm2cpio"
# rpm2cpio does not have a '--' separator between options and filename, at least as of version 4.17.0 .
local CMD
printf -v CMD \
"%q %q | cpio --extract --make-directories --preserve-modification-time --quiet" \
"$UNCOMPRESS_TOOL" \
"$ARCHIVE_FILENAME_ABS"
echo "$CMD"
eval "$CMD"
}
unpack_rar ()
{
# Tool unrar-free only supports plain RAR 2.0 files, and the first .rar file
# I tried to unpack had format version 5.
local UNCOMPRESS_TOOL="unrar"
verify_tool_is_installed "$UNCOMPRESS_TOOL" "unrar"
local CMD
printf -v CMD \
"%q x -- %q" \
"$UNCOMPRESS_TOOL" \
"$ARCHIVE_FILENAME_ABS"
echo "$CMD"
eval "$CMD"
}
# ------- Entry point -------
USER_SHORT_OPTIONS_SPEC=""
# Use an associative array to declare how many arguments every long option expects.
# All known options must be listed, even those with 0 arguments.
declare -A USER_LONG_OPTIONS_SPEC
USER_LONG_OPTIONS_SPEC+=( [help]=0 )
USER_LONG_OPTIONS_SPEC+=( [version]=0 )
USER_LONG_OPTIONS_SPEC+=( [license]=0 )
# Populate the list with all supported filename extensions before processing
# the command-line options, because the '--help' option uses this list.
declare -A ALL_EXTENSIONS
add_all_extensions
parse_command_line_arguments "$@"
case "${#ARGS[@]}" in
1) declare -r OUTPUT_DIRNAME="$PWD";;
2) declare -r OUTPUT_DIRNAME="${ARGS[1]}";;
*) abort "Invalid number of command-line arguments. Run this tool with the --help option for usage information.";;
esac
if [ ! -d "$OUTPUT_DIRNAME" ]; then
abort "Output directory does not exist: $OUTPUT_DIRNAME"
fi
declare -r ARCHIVE_FILENAME="${ARGS[0]}"
# readlink below will print an error message if the archive does not exist,
# so we do not need to do it ourselves.
if false; then
if ! [ -f "$ARCHIVE_FILENAME" ]; then
abort "Archive \"$ARCHIVE_FILENAME\" does not exist."
fi
fi
ARCHIVE_FILENAME_ABS="$(readlink --canonicalize-existing --verbose -- "$ARCHIVE_FILENAME")"
# Sometimes I do not realise that the archive has already been uncompressed:
# I just type the first filename letters, press the Tab key for autocompletion,
# and run this script without really looking. The "Unknown archive type" error message
# comes as then a surprise, and it takes a couple of seconds forme to realise what is going on.
#
# In order to prevent that from happening yet again, I added this check, which
# generates a better error message in this common scenario.
if [ -d "$ARCHIVE_FILENAME_ABS" ]; then
abort "File \"$ARCHIVE_FILENAME\" is actually a directory."
fi
LONGEST_EXTENSION_MATCH=""
UNPACK_FUNCTION=""
# Do a case-insensitive match, because under Microsoft Windows we could see
# the known extension ins uppercase.
ARCHIVE_FILENAME_LOWER_CASE="${ARCHIVE_FILENAME,,}"
# There may be several matches, like ".gz and ".tar.gz". In that case,
# take the longest.
for KEY in "${!ALL_EXTENSIONS[@]}"
do
KEY_IN_LOWER_CASE="${KEY,,}"
if str_ends_with "$ARCHIVE_FILENAME_LOWER_CASE" "$KEY_IN_LOWER_CASE"; then
if (( ${#KEY} > ${#LONGEST_EXTENSION_MATCH} )); then
UNPACK_FUNCTION="${ALL_EXTENSIONS[$KEY]}"
LONGEST_EXTENSION_MATCH="$KEY"
if false; then
echo "Unpack function found for '$LONGEST_EXTENSION_MATCH': $UNPACK_FUNCTION"
fi
fi
fi
done
if [ -z "$UNPACK_FUNCTION" ]; then
abort "Unknown archive type for filename \"$ARCHIVE_FILENAME\"."
fi
declare -r ARCHIVE_NAME_ONLY="${ARCHIVE_FILENAME##*/}"
declare -r -i EXT_LEN="${#LONGEST_EXTENSION_MATCH}"
declare -r ARCHIVE_NAME_ONLY_WITHOUT_EXT="${ARCHIVE_NAME_ONLY::-$EXT_LEN}"
TMP_DIRNAME="$(mktemp --directory --dry-run -- "$OUTPUT_DIRNAME/$ARCHIVE_NAME_ONLY_WITHOUT_EXT-unpacked-XXXXX")"
# Using mktemp's --dry-run is considered unsafe, but this is OK for this script.
# The trouble is, mktemp would create the subdirectory with very restrictive permissions.
# If we create it ourselves, the new subdirectory gets the default permissions,
# and that is what we want.
# We could let mktemp create the subdirectory and then use "chmod --reference=xxx" to copy
# the permissions from something else, but is is not clear what we could take as reference.
mkdir -- "$TMP_DIRNAME"
echo "Unpacking $ARCHIVE_FILENAME ..."
pushd "$TMP_DIRNAME" >/dev/null
set +o errexit
# Start a subshell for error-handling purposes: the routine called should fail straight away if
# any of the commands inside it fails, but we need to capture the error and carry on at the top-level.
(
set -o errexit
set -o nounset
set -o pipefail
"$UNPACK_FUNCTION"
)
declare -r -i UNPACK_EXIT_CODE="$?"
set -o errexit
popd >/dev/null
echo
if false; then
echo "Analysing unpacked files..."
fi
shopt -s nullglob
shopt -s dotglob # Include hidden files.
declare -a FILES_IN_TMP_DIR=( "$TMP_DIRNAME"/* )
if false; then
for FILENAME in "${FILES_IN_TMP_DIR[@]}"
do
echo "Filename: $FILENAME"
done
fi
declare -r -i UNPACKED_FILE_COUNT="${#FILES_IN_TMP_DIR[@]}"
declare -r TMP_DIRNAME_JUST_NAME="${TMP_DIRNAME##*/}"
if (( UNPACK_EXIT_CODE != 0 )); then
if (( UNPACKED_FILE_COUNT == 0 )); then
# We need to print some error message at all, just in case.
# For example, UnZip 6.00 under Linux does not print the following error message
# if we are using flag -q (quiet). We are using -q because otherwise the output is too verbose:
# Archive: test.zip
# skipping: test.txt need PK compat. v5.1 (can do v4.6)
# With the -q flag, nothing is output at all, and the exit code is then 81.
echo "Unpacking failed."
rmdir -- "$TMP_DIRNAME"
else
echo "Unpacking failed. Some unpacked files have been left in subdirectory:"
echo " $TMP_DIRNAME_JUST_NAME/"
fi
exit "$UNPACK_EXIT_CODE"
fi
if (( UNPACKED_FILE_COUNT == 0 )); then
# While theoretically possible, this should never happen in real life.
rmdir -- "$TMP_DIRNAME"
abort "The archive has no files inside."
fi
if (( UNPACKED_FILE_COUNT == 1 )); then
declare -r THE_ONLY_FILENAME="${FILES_IN_TMP_DIR[0]}"
if [ -d "$THE_ONLY_FILENAME" ]; then
# If there is one single directory, keep its name.
JUST_NAME="${THE_ONLY_FILENAME##*/}"
if [ -e "$OUTPUT_DIRNAME/$JUST_NAME" ]; then
echo "Archive unpacked into subdirectory:"
echo " $TMP_DIRNAME_JUST_NAME/"
echo "because file or subdirectory \"$JUST_NAME\" already existed."
else
mv -- "$THE_ONLY_FILENAME" "$OUTPUT_DIRNAME/"
rmdir -- "$TMP_DIRNAME"
echo "Archive unpacked into subdirectory:"
echo " $JUST_NAME/"
fi
exit $EXIT_CODE_SUCCESS
fi
if [ -f "$THE_ONLY_FILENAME" ]; then
JUST_NAME="${THE_ONLY_FILENAME##*/}"
if [ -e "$OUTPUT_DIRNAME/$JUST_NAME" ]; then
echo "Archive unpacked into subdirectory:"
echo " $TMP_DIRNAME_JUST_NAME/"
echo "because file or subdirectory \"$JUST_NAME\" already existed."
else
mv -- "$THE_ONLY_FILENAME" "$OUTPUT_DIRNAME/"
rmdir -- "$TMP_DIRNAME"
echo "Only one file was unpacked. The resulting filename is:"
echo " $JUST_NAME"
fi
exit $EXIT_CODE_SUCCESS
fi
fi
declare -r DEST_DIR="$OUTPUT_DIRNAME/$ARCHIVE_NAME_ONLY_WITHOUT_EXT"
if [ -e "$DEST_DIR" ]; then
echo "Archive unpacked into subdirectory:"
echo " $TMP_DIRNAME_JUST_NAME/"
echo "because file or subdirectory \"$ARCHIVE_NAME_ONLY_WITHOUT_EXT\" already existed."
else
mv -- "$TMP_DIRNAME" "$DEST_DIR"
echo "Archive unpacked into subdirectory:"
echo " $ARCHIVE_NAME_ONLY_WITHOUT_EXT/"
fi