Quantcast
Channel: User Kamil Maciorowski - Super User
Viewing all articles
Browse latest Browse all 837

Answer by Kamil Maciorowski for How to move one file from a list and rename it?

$
0
0

There is already a working answer, sub-optimal though. Breaking out of a for loop seems unnecessarily complicated. You can create an array without a loop. In the following example we set anew the array of positional parameters; we do it in a subshell, so the main shell is not affected.

(shopt -s failglob   # not portableset -- /path/to/pi-hole-srv-teleporter_* && echo mv -- "$1" /backup/teleporter.tar.gz)

The script as-is is a no-op. Remove the echo to "arm" it.

Notes:

  • shopt -s failglob will make the expansion of * fail if there is no match, then mv will not be attempted at all. Without failglob and without a match the pattern would stay verbatim and it would get to mv as such. In our case it would not be so bad (mv would just fail), but in general it's often better to detect the situation early.
  • The expansion of * sorts the matching pathnames, set stores them in that order as positional parameters. In our code we use the first one: $1. You can easily get the last one: ${!#}. The filenames in question are designed well, they will be sorted by the embedded timestamp. All this means you can pick the oldest or the newest file easily.

Viewing all articles
Browse latest Browse all 837

Trending Articles