Можно ли использовать rsync для исключения целых каталогов и подсодержимого только в том случае, если он содержит файл, соответствующий шаблону?

Si todo lo que desea hacer es obtener la lista de archivos en el directorio actual y luego agregar una cadena a cada uno de estos nombres:

set -- *
printf '%s-somestring\n' "$@"

o, usando una matriz bash,

names=( * )
printf '%s-somestring\n' "${names[@]}"

Usar una matriz, ya sea la matriz de parámetros posicionales (el primer ejemplo anterior, que funcionará en todos los shells POSIX ), o una matriz bash, es la forma más segura de trabajar con nombres de archivo. Si está convirtiendo los nombres de archivo en algún tipo de cadena delimitada, tendrá problemas cuando tenga nombres de archivo que contengan cualquier carácter que haya elegido para delimitar la cadena.

Para solo agregar algo al final de la salida , hágalo en un separadoecho:

# code that output something
# then,
echo 'additional data'

O, modificando mis ejemplos de arriba:

set -- * 'additional data'
printf '%s\n' "$@"

y

names=( * 'additional data' )
printf '%s\n' "${names[@]}"

O...

set -- *
set -- "$@" 'additional data'
printf '%s\n' "$@"

y

names=( * )
names+=( 'additional data' )
printf '%s\n' "${names[@]}"
1
31.07.2019, 06:26
1 ответ

Благодаря советам от cas я смог создать этот рабочий процесс для решения проблемы с bash-скриптом. Это не идеально, потому что было бы лучше, если бы он сделал шаг для более быстрой работы (. Я бы хотел, чтобы у rsync была такая возможность ). Сценарий будет искать под текущей папкой файлы с помощью find, создавать список исключений, а затем использовать rsync из базового тома для перемещения всех остальных папок в папку для мусора, сохраняя полный путь под ним, чтобы любые ошибки можно было восстановить без разрушения.

Ссылка на текущее состояние, если это решение находится в ветке git dev-https://github.com/firehawkvfx/openfirehawk-houdini-tools/blob/dev/scripts/modules/trashcan.sh

#!/bin/bash

# trash everything below the current path that does not have a.protect file in
# the folder.  it should normally only be run from the folder such as
# 'job/seq/shot/cache' to trash all data below this path.

# see opmenu and firehawk_submit.py for tools to add protect files based on
# a top net tree for any given hip file.

argument="$1"

echo ""
ARGS=''

if [[ -z $argument ]] ; then
  echo "DRY RUN. To move files to trash, use argument -m after reviewing the exclude_list.txt and you are sure it lists everything you wish to protect from being moved to the trash."
  echo ""
  ARGS1='--remove-source-files'
  ARGS2='--dry-run'
else
  case $argument in
    -m|--move)
      echo "MOVING FILES TO TRASH."
      echo ""
      ARGS1='--remove-source-files'
      ARGS2=''
      ;;
    *)
      raise_error "Unknown argument: ${argument}"
      return
      ;;
  esac
fi

current_dir=$(pwd)
echo "current dir $current_dir"
base_dir=$(pwd | cut -d/ -f1-2)
echo "base_dir $base_dir"


source=$(realpath --relative-to=$base_dir $current_dir)/
echo "source $source"
target=trash/
echo "target $target"

# ensure trash exists at base dir.
mkdir -p $base_dir/$target
echo ""
echo "Build exclude_list.txt contents with directories containing.protect files"
find. -name.protect -print0 |
    while IFS= read -r -d '' line; do
        path=$(realpath --relative-to=. "$line")
        dirname $path
    done > exclude_list.txt

path_to_list=$(realpath --relative-to=. exclude_list.txt)
echo $path_to_list >> exclude_list.txt

cat exclude_list.txt

cd $base_dir

# run this command from the drive root, eg /prod.
rsync -a $ARGS1 --prune-empty-dirs --inplace --relative --exclude-from="$current_dir/exclude_list.txt" --include='*' --include='*/' $source $target $ARGS2 -v
cd $current_dir
1
27.01.2020, 23:41

Теги

Похожие вопросы