使用变量作为目录路径在 bash 中重定向输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22696548/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using a variable as a directory path to redirect output in bash
提问by user3351901
I am trying to write a script that will allow the user to input the path of the directory to which they want to store a file. I have something that looks like this:
我正在尝试编写一个脚本,允许用户输入他们想要存储文件的目录的路径。我有一些看起来像这样的东西:
#! /bin/bash
echo "Enter the directory path"
read varpath
varfile="Filename"
echo "This is a file" > "$varpath$varfile"
what I want is a file in the directory path the user entered called "Filename" and has the line "This is a file" However, I am getting an error saying that there is not such file or directory. Can someone tell me whats wrong, or if there's an alternate solution to this.
我想要的是用户输入的目录路径中的一个名为“文件名”的文件,并且有一行“这是一个文件”但是,我收到一个错误消息,说没有这样的文件或目录。有人可以告诉我出了什么问题,或者是否有其他解决方案。
Thanks.
谢谢。
回答by Amit Verma
Proabably you need a /
.
可能你需要一个/
.
echo "This is a file" > "${varpath}/${varfile}"
You can also echo
the variables to make sure they are correct
您还可以echo
使用变量来确保它们是正确的
回答by Shreyas Purohit
Few things you might want to handle:
您可能想要处理的几件事:
The user input directory has the required folders, if not create them using
mkdir -p
command.The user enters dir path that either ends with / or not. If not, you might want to add it yourself.
用户输入目录具有所需的文件夹,如果没有使用
mkdir -p
命令创建它们。用户输入以 / 或不以 / 结尾的目录路径。如果没有,您可能想自己添加它。