如何使用bash脚本安装包含变量的bash函数?

编程入门 行业动态 更新时间:2024-10-26 03:31:16
本文介绍了如何使用bash脚本安装包含变量的bash函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试创建一个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函数?

本文发布于:2023-06-07 20:54:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/595010.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   变量   脚本   函数   bash

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!