OK, so all I really want to do is backup single files as a time in the current directory with '.bak' extension.

Here is my current function that does this (jsyk, using Rocky Linux):

function backup { sudo cp $PWD/$1 $PWD/$1.bak; }

Although, Rocky loads it fine (it's inside ~/.bash_aliases which is loaded from ~/.bashrc, it seems to keep giving me this error:

cp: cannot stat '.bak': No such file or directory

Am I missing something? Or am I crazy for not thinking of something even simpler?

  • 1
    sudo requires -E and -H to preserve environment variables and cp requires -a and -f to keep files metadata and forces overwrite existing .bak
    – alecxs
    Mar 18, 2022 at 18:07
  • @alecxs if I’m understanding you, it should be “sudo -EH cp -af …”, if so, didn’t work.
    – GregTheHun
    Mar 18, 2022 at 18:12
  • 1
    Well, they aren't local variables, $PWD gives me the current working directory, and $1 I thought was used for posititional variables. Testing this, I used: function test { sudo -EH echo $PWD/$1.bak; } Which seems to give me the proper output: /home/greg/file.txt.bak
    – GregTheHun
    Mar 18, 2022 at 18:19
  • 1
    You could always use echo to get an idea what the command looks like after expansion. Mar 18, 2022 at 18:37

1 Answer 1


Thanks @alecxs, this seemed to work for me:

function backup() { sudo -EH cp -af -- "$1" "$1.bak"; }

You must log in to answer this question.

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