Bash 脚本,将输出重定向到另一个目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23663907/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 10:26:39  来源:igfitidea点击:

Bash script, redirect output to another directory

linuxbash

提问by Bubo

I have an environment variable containing the name of a directory. I am trying to redirect output from an echo command to a text file in a different directory.

我有一个包含目录名称的环境变量。我正在尝试将 echo 命令的输出重定向到不同目录中的文本文件。

For example

例如

DIR="NewDirectory"
mkdir $DIR
echo "Testing" >> "$DIR\file.txt"

Results in a file named NewDirectory\file.txt in the working directory of the script...what exactly am I missing here? The directory is created without issue, so I am not sure what is going on here.

结果在脚本的工作目录中出现了一个名为 NewDirectory\file.txt 的文件......我在这里错过了什么?该目录的创建没有问题,所以我不确定这里发生了什么。

回答by gipinani

You have to change \into /:

您必须更改\/

DIR="NewDirectory"
mkdir -p $DIR
echo "Testing" >> "$DIR/file.txt"

Changed mkdir -pas suggested by @Jord, because -pmeans: no error if existing, make parent directories as needed

改变mkdir -p由@Jord的建议,因为-p手段:没有错误,如果现有的,根据需要进行的父目录

回答by Mureinik

In linux(or unixfor that matter), the directory separator is a slash (/), not a backslash (\):

linux(或unix)中,目录分隔符是斜杠 ( /),而不是反斜杠 ( \):

DIR="NewDirectory"
mkdir $DIR
echo "Testing" >> "$DIR/file.txt"

回答by damienfrancois

Your line

你的线路

echo "Testing" >> "$DIR\file.txt"

should read

应该读

echo "Testing" >> "$DIR/file.txt"

as /is the separator in paths in Linux.

就像/Linux中路径中的分隔符一样。