| 1 |
#!/bin/bash |
| 2 |
|
| 3 |
set -eu |
| 4 |
|
| 5 |
# Function to show usage |
| 6 |
show_usage() { |
| 7 |
echo "Usage: $0 [--dry-run|-n] --move-to DIRNAME directory [directory2 ...]" |
| 8 |
} |
| 9 |
|
| 10 |
# On OSX we better use GNU one |
| 11 |
if [ -e /usr/local/opt/gnu-getopt/bin/getopt ]; then |
| 12 |
getopt=/usr/local/opt/gnu-getopt/bin/getopt |
| 13 |
else |
| 14 |
getopt=getopt |
| 15 |
fi |
| 16 |
|
| 17 |
# Parsing options |
| 18 |
TEMP=$("$getopt" -o 'n' --long move-to:,dry-run -n "$(basename "$0")" -- "$@") |
| 19 |
# shellcheck disable=SC2181 |
| 20 |
if [ $? != 0 ]; then echo "Terminating..." >&2; exit 1; fi |
| 21 |
|
| 22 |
# Note the quotes around `$TEMP`: they are essential! |
| 23 |
eval set -- "$TEMP" |
| 24 |
|
| 25 |
# Initialize variables |
| 26 |
MOVE_TO_DIR="" |
| 27 |
DRY_RUN="" |
| 28 |
|
| 29 |
# Extract options and their arguments into variables |
| 30 |
while true; do |
| 31 |
case "$1" in |
| 32 |
--move-to) |
| 33 |
MOVE_TO_DIR="$2" |
| 34 |
shift 2 |
| 35 |
;; |
| 36 |
-n|--dry-run) |
| 37 |
DRY_RUN=1 |
| 38 |
shift |
| 39 |
;; |
| 40 |
--) |
| 41 |
shift |
| 42 |
break |
| 43 |
;; |
| 44 |
*) |
| 45 |
echo "Internal error!" |
| 46 |
exit 1 |
| 47 |
;; |
| 48 |
esac |
| 49 |
done |
| 50 |
|
| 51 |
# Check for mandatory option |
| 52 |
if [ -z "$MOVE_TO_DIR" ]; then |
| 53 |
echo "Error: --move-to option is required." |
| 54 |
show_usage |
| 55 |
exit 1 |
| 56 |
fi |
| 57 |
|
| 58 |
# Create MOVE_TO_DIR if it does not exist |
| 59 |
if [ ! -d "$MOVE_TO_DIR" ]; then |
| 60 |
mkdir -p "$MOVE_TO_DIR" |
| 61 |
fi |
| 62 |
|
| 63 |
TEMP=$(mktemp -d "${TMPDIR:-/tmp}/dl-XXXXXXX") |
| 64 |
|
| 65 |
# Process the remaining arguments (directories) |
| 66 |
for dir in "$@"; do |
| 67 |
echo "" |
| 68 |
echo "Processing directory: $dir" |
| 69 |
rm -rf "${TEMP:?}/*" |
| 70 |
failed= |
| 71 |
dcm2niix -z y -b y -o "$TEMP/" "$dir" 2>"$TEMP/stderr" >"$TEMP/stdout" || { |
| 72 |
echo " Exited with $?; We will proceed with the analysis. Standard error output was:" |
| 73 |
sed -e 's,^, ,g' "$TEMP/stderr" |
| 74 |
} |
| 75 |
|
| 76 |
if grep "Error: Check sorted order: 4D dataset has" "$TEMP/stderr"; then |
| 77 |
failed=1 |
| 78 |
fi |
| 79 |
if grep "Error: Missing images." "$TEMP/stderr"; then |
| 80 |
failed=1 |
| 81 |
fi |
| 82 |
if [ -n "$failed" ]; then |
| 83 |
if [ -n "$DRY_RUN" ]; then |
| 84 |
echo mv "$dir" "$MOVE_TO_DIR" |
| 85 |
else |
| 86 |
echo " Moving $dir to $MOVE_TO_DIR" |
| 87 |
mv "$dir" "$MOVE_TO_DIR" |
| 88 |
fi |
| 89 |
fi |
| 90 |
done |