How to install a bash function containing variables using a bash script? [duplicate]

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-02 21:51:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!