-1

I am trying to create an alias in my bash profile such that I can call backup_dir Playground and have it complete: cp -r Playground $HOME/BACKUP

I would also like to ensure that if the file/directory is of the same name it is just overwritten.

The code I input in my bash_profile is as follows: alias backup='cp $2 $HOME/BACKUP/$2' alias backup_dir='cp -r $2 $HOME/BACKUP/$2'

I also tried it with $1 but it did not work either.

What actually occurs is that it copies the contents of my backup directory and creates it in the directory I'm supposed to be copying/copying from.

Abhi Rai
  • 9
  • 3

1 Answers1

0

Aliases don't really take arguments, and trying to define aliases as if they did winds up in strange territory (if you define a simple alias 'foo' that just echos instead of copies, you'll find it reversed the order of the arguments you passed - i.e. the first argument is the backup directory and the second is the directory you wanted.) I'm guessing the details of why that happens aren't super interesting to you - but that is... 'expected'.

The solution is to write a function to use in your alias, or to write a small shell script and call that instead.

Aliases really substitute 'bash' as the command that then executes the string you pass (if you echo $0 instead of $1, you'll see something like 'bash foo' as the output).

More detailed instructions can be found in the ubuntu forums (for example)

  • 2
    Please do not "write a function to use in your alias". Delete the alias (`unalias`), write a function that does the job directly, and forget you ever heard of aliases. For almost any purpose one might want to use an alias for, a function is a better-or-equally-good replacement. You certainly don't need to combine them; that's just adding confusion. – Gordon Davisson Oct 27 '22 at 18:54
  • See also [Why would I create an alias which creates a function?](https://stackoverflow.com/questions/57239089/why-would-i-create-an-alias-which-creates-a-function) – tripleee Oct 28 '22 at 06:35
  • Fair point... I use aliases when I want to interact with bash history, or other bash features (e.g. scan the history to look for something and act accordingly). I'll write a script or function to do the work, then use an alias to send the history to it. – Chris Ebert Oct 28 '22 at 22:30