【问题标题】:Error when outputting to file name variable in shell script输出到 shell 脚本中的文件名变量时出错
【发布时间】:2011-01-26 21:51:46
【问题描述】:

我编写了一个非常简单的程序来测试将数据输出到文件名变量。

#!/bin/sh
file="~/output"
echo "test" > $file

当我运行这个脚本时,我得到了以下错误

"./script.sh: line 3: ~/output: No such file or directory"

那么我应该如何修改我的代码以使其正常工作?还是shell脚本不支持?

【问题讨论】:

    标签: unix scripting


    【解决方案1】:

    “~/output”周围的引号让你很伤心。

    例如

    #!/bin/sh
    file=~/output
    echo "test" > $file
    

    工作正常。

    要查看发生了什么,请尝试

    $ file="~/output"
    $ echo $file
    

    $ file=~/output
    $ echo $file
    

    请记住,~ 是主目录的 shell 扩展。

    【讨论】:

      【解决方案2】:

      您可以在脚本中使用 $HOME 环境变量:

      #!/bin/sh
      file="$HOME/output"
      echo "test" > $file
      

      【讨论】:

        猜你喜欢
        • 2015-05-30
        • 1970-01-01
        • 1970-01-01
        • 2012-08-17
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        • 2013-12-13
        • 2017-06-13
        相关资源
        最近更新 更多