【问题标题】:how to echo without being executed如何在不执行的情况下回显
【发布时间】:2015-08-14 19:29:05
【问题描述】:

我正在尝试在 /etc/profile 中添加 echo 语句,但它们会执行。

例子:这是我写的

echo CURRENTYEAR="`/bin/date +%y`" >> /etc/profile 
    echo  CURRENTWEEK="`/bin/date +%V` " >> /etc/profile
    echo VERSION="$CURRENTYEAR"."$CURRENTWEEK" >> /etc/profile
    echo export VERSION >> /etc/profile



      echo export SVN_HOME="https://example.com/svn/road" >> /etc/profile
      echo SVN_BRANCH="$SVN_HOME/branches/qa_weekly/$VERSION" >> /etc/profile
      echo export SVN_TAG="https://example.cpm/svn/road/tags" >> /etc/profile
      echo export SVN_TRUNK="https://example.com/svn/empire/trunk" >> /etc/profile
     export PATH=$PATH:/road >> /etc/profile
     export SVN_BRANCH

结果:我得到了什么

CURRENTYEAR=15
CURRENTWEEK=33
VERSION=.
export VERSION
export SVN_HOME=https://example.com/svn/road
SVN_BRANCH=/branches/qa_weekly/
export SVN_TAG=https://example.com/svn/road/tags
export SVN_TRUNK=https://example.com/svn/road/trunk

我希望它在 /etc/profile 中如下所示

CURRENTYEAR=`/bin/date +%y`
CURRENTWEEK=`/bin/date +%V`
VERSION=$CURRENTYEAR"."$CURRENTWEEK
export VERSION

SVN_BRANCH=$SVN_HOME/branches/qa_weekly/$VERSION
SVN_TAG=$SVN_HOME/tags
SVN_TRUNK=$SVN_HOME/trunk

提前致谢。

【问题讨论】:

  • 为什么不在文本编辑器中打开 /etc/profile 并将其全部写入其中?
  • 我使用的是 chef,所以我需要在那里添加脚本,以便它附加到我使用 chef 创建的每个服务器
  • 在这种情况下,我建议接受格伦杰克曼的回答。

标签: bash shell export echo


【解决方案1】:

将您的字符串放在单引号中:

echo 'CURRENTYEAR="`/bin/date +%y`"' >> /etc/profile
#....^.............................^

http://www.gnu.org/software/bash/manual/bashref.html#Single-Quotes

将字符括在单引号中保留引号内每个字符的字面值。单引号之间可能不会出现单引号,即使前面有反斜杠。

【讨论】:

    【解决方案2】:

    不要使用多个 echo 语句,而是使用 cat 和此处引用的文档:

    cat >> /etc/profile <<'EOF'
    CURRENTYEAR=`/bin/date +%y`
    CURRENTWEEK=`/bin/date +%V`
    VERSION="$CURRENTYEAR.$CURRENTWEEK"
    export VERSION
    export SVN_HOME="https://example.com/svn/road"
    SVN_BRANCH="$SVN_HOME/branches/qa_weekly/$VERSION"
    export SVN_TAG="https://example.cpm/svn/road/tags" 
    export SVN_TRUNK="https://example.com/svn/empire/trunk"
    export PATH=$PATH:/road
    export SVN_BRANCH
    EOF
    

    在第一行引用EOF 可以防止在此处文档的正文中发生任何替换。

    【讨论】:

      猜你喜欢
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-25
      • 2017-08-03
      • 1970-01-01
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多