代码之家  ›  专栏  ›  技术社区  ›  Blebhebhe

创建创建另一个脚本的脚本

  •  0
  • Blebhebhe  · 技术社区  · 7 年前

    我想制作一个脚本,在存储的文件夹中创建一个文件

    在这里,我存储了库存香蕉的文件夹路径 然后我想在那个文件夹中创建一个文件

    echo "stock=banana/" >> test.sh
    echo "touch $stock/file" >> test.sh
    

    当我打开测试时。上海:

    stock=banana/
    touch /file
    

    为什么不是呢 $stock 那里

    1 回复  |  直到 7 年前
        1
  •  1
  •   Charles Duffy    7 年前

    做对了

    如果要插入的内容是硬编码的,请使用引号:

    # Because of the quotes around EOF, nothing inside this heredoc is modified.
    cat >test.sh <<'EOF'
    stock=banana/
    touch "$stock/file"
    EOF
    

    如果是 硬编码,则无引号的ELEDOC变得合适——但需要一些注意:

    #!/bin/bash
    #      ^^^^-- /bin/sh does not support any means of eval-safe quoting
    #             ...a ksh derivative such as bash will provide printf %q
    
    stock=banana/                    # Presumably this is coming from a generic source, ie. $1
    printf -v stock_q '%q' "$stock"  # Generate an eval-safe quoted version of stock
    
    # Because the sigil is not quoted, expansions inside the heredoc are performed unless
    # they're escaped.
    cat >test.sh <<EOF
    stock=$stock_q
    touch "\$stock/file"
    EOF
    

    注意,我们正在使用 printf %q 生成值的安全转义版本并插入 那个 $stock 具有 \$stock ).

    回答“为什么”

    "$stock" 在传递给之前,由原始shell扩展 echo .