我正在尝试创建一个bash脚本,该脚本将允许我在多台计算机上安装相同的bash函数.此特定功能在备份目录中创建带有时间戳的文件副本:
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"; }这是我的bash脚本:
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但是,当我执行脚本时,缺少${@}并且已经评估了$(date +%Y-%m-%d_%H:%M:%S).这是已添加到.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?
推荐答案此处的文档被视为双引号字符串,因此在从命令读取参数扩展和命令替代之前先对其进行评估.引用定界符的任何部分,以将此处文档视为单引号字符串.
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
- 'EOT'
- E\OT
- "E"OT
等等.
更多推荐
如何使用bash脚本安装包含变量的bash函数?
发布评论