问题
I am attempting to create a bash script that will allow me to install the same bash function across multiple machines. This particular function creates a copy of a file with a timestamp in a backup directory:
filebackup () { cp "${@}" ~/"filebackup/${@}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
Here is my bash script:
cat <<EOT >> ~/.bashrc
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "${@}" ~/"filebackup/${@}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
EOT
source ~/.bashrc
When I execute the script, however, the ${@}
are missing and the $(date +%Y-%m-%d_%H:%M:%S)
has been evaluated. Here is what has been appended to the .bashrc
file:
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "" ~/"filebackup/_2017-01-05_12:07:56.bk"; }
How can I ensure that the function is copied literally into the file?
回答1:
A here document is treated as a double-quoted string, so parameter expansions and command substitutions are evaluated before the command reads from them. Quote any part of the delimiter to have the here document treated as a single-quoted string.
cat <<\EOT >> ~/.bashrc
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "${@}" ~/"filebackup/${@}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
EOT
By any part, I mean any of the following would work just as well:
'EOT'
E\OT
"E"OT
et cetera.
回答2:
Suggested by @thatotherguy in a comment: quote "EOT" on line 1 (but not on line 6).
cat <<"EOT" >> ~/.bashrc
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# create a file backup in ~/filebackup/ with timestamp
filebackup () { cp "${@}" ~/"filebackup/${@}_$(date +%Y-%m-%d_%H:%M:%S).bk"; }
EOT
source ~/.bashrc
来源:https://stackoverflow.com/questions/41490895/how-to-install-a-bash-function-containing-variables-using-a-bash-script