1

I need to backup files (usually images) before editing (and overwrite) them.
Currently I do it by:

cp file.jpg ~/BACKUP/file.jpg
exiv2 BLABLABLA file.jpg

How can I do it with a single command?
e.g.

AAalias file.jpg

where AAalias is an alias or a function, doesn't matter but this is the shape I'm looking for: command + filename

3
  • define command. single press of enter?
    – erik258
    Commented Oct 3, 2019 at 15:54
  • yes, I update OP
    – mattia.b89
    Commented Oct 3, 2019 at 16:13
  • 1
    It's not really clear what is AAalias but @Kusalanada answer should work like bash alias and do it in single command.
    – Shmuel
    Commented Oct 3, 2019 at 16:19

2 Answers 2

3

Using a shell function:

backup_and_edit () {
    cp -i "$1" "$HOME/BACKUP" &&
    exiv2 BLABLABLA "$1"
}

This would go where you usually put aliases and shell function (probably in your ~/.bashrc file), and after having instantiated the function (by starting a new shell session), you would use it like

$ backup_and_edit ./some/file.jpg

When invoked like this, the function would execute

cp -i ./some/file.jpg "$HOME/BACKUP" &&
exiv2 BLABLABLA ./some/file.jpg

The -i option to cp would make the utility ask for confirmation before over-writing a file with the same name in your backup directory. If the copy fails, the exiv2 command would not be invoked.

1
  • I have this backup function: backup() { for file in "$@"; do local new="${file}.$(date '+%Y%m%d')"; while [[ -f "$new" ]]; do new+="~"; done; printf "copying '%s' to '%s'\n" "${file}" "$new"; \cp -ip "$file" "$new"; done; } Commented Oct 4, 2019 at 12:03
0

You can create an alias, that uses a function:

alias Aalias='_(){ local file=${@: -1};(($#<2))||[[ ! -e "${file}" ]]&&echo "Usage: Aalias <options> <file>"&&return 1;cp "${file}" ~/BACKUP/${file};exiv2 $@;}; _'

${@: -1} grabs the last argument for the file 
[[ ! -e "${file}" ]] checks to make sure the file exists 

Usage will be shown if less than 2 arguments are provided or the file doesn't exist.

If the last argument is the name of a file that exists it will be backed up to the BACKUP directory in user's home and exiv2 will be launched with the options provided on the commandline.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .