[英]Bash. Redirecting output of grep into file
I have a basic bash script that i want to use to create a list of directories inside a file.我有一个基本的 bash 脚本,我想用它来创建文件内的目录列表。 The issue is that when i type the following command on the terminal it works fine but when used inside a function it does not问题是,当我在终端上键入以下命令时,它工作正常,但在函数内部使用时却没有
function Create_file_dirs()
{
ls | grep / > dirs.txt
cat dirs.txt #used for debugging
}
This function is inside a script and i'm running it by calling the script.这个函数在一个脚本中,我通过调用脚本来运行它。 ./script.sh ./script.sh
` `
The command ls | grep / > dirs.txt
命令ls | grep / > dirs.txt
ls | grep / > dirs.txt
works great on the terminal window and produces a file listing directories line by line, but doesn't do anything when used inside a function and i can't figure out why. ls | grep / > dirs.txt
在终端窗口上运行良好,并生成一个逐行列出目录的文件,但在函数内部使用时不执行任何操作,我不知道为什么。 Thanks谢谢
ls
without options does not produce slashes, so grep doesn't find anything. ls
不带选项不会产生斜杠,所以 grep 找不到任何东西。 You can easily reproduce it on the command line by, say,你可以很容易地在命令行上重现它,比如,
comand ls|grep /
My thanks to William Pursell for his answer and to everyone who contributed.感谢 William Pursell 的回答以及所有做出贡献的人。
The answer came from a comment made by William Pursell.答案来自 William Pursell 的评论。 The working function is:工作函数是:
create_file_dirs()
{
ls -F | grep / >./dirs.txt
cat dirs.txt
}
The issue was,that when i was running the ls command on the terminal i could see a slash / after a directories name and running the command on the terminal actually produced the desired result.问题是,当我在终端上运行 ls 命令时,我可以在目录名称之后看到一个斜杠 / 并且在终端上运行该命令实际上产生了所需的结果。
ls | grep / > ./dirs.txt
It seems though running ls through a script doesn't produce a slash / after a directories name that is why i had to add them -F option to resolve this issue.虽然通过脚本运行 ls 似乎不会在目录名称之后产生斜杠 / 这就是为什么我必须添加它们 -F 选项来解决这个问题。
The way i tested it out was with this simple function inside a script and run the script.我测试它的方法是在脚本中使用这个简单的函数并运行脚本。 The result didn't have slashes.结果没有斜线。
test_dirs(){
ls | cat
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.