在 bash 中使用命令的结果作为参数? [英] Using the result of a command as an argument in bash?

查看:24
本文介绍了在 bash 中使用命令的结果作为参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要为文件夹中的所有音乐创建播放列表,我在 bash 中使用以下命令:

To create a playlist for all of the music in a folder, I am using the following command in bash:

ls > list.txt

我想使用 pwd 命令的结果作为播放列表的名称.

I would like to use the result of the pwd command for the name of the playlist.

类似于:

ls > ${pwd}.txt

但这不起作用 - 谁能告诉我我需要使用什么语法来做这样的事情?

That doesn't work though - can anyone tell me what syntax I need to use to do something like this?

正如评论中提到的,pwd 最终会给出一个绝对路径,所以我的播放列表最终会在某个目录中被命名为 .txt - 天哪!所以我必须修剪路径.感谢您发现这一点 - 我可能会花很长时间想知道我的文件去了哪里!

As mentioned in the comments pwd will end up giving an absolute path, so my playlist will end up being named .txt in some directory - d'oh! So I'll have to trim the path. Thanks for spotting that - I would probably have spent ages wondering where my files went!

推荐答案

最好的方法是使用 "$(command替换)"(谢谢,兰登):

The best way to do this is with "$(command substitution)" (thanks, Landon):

ls > "$(pwd).txt"

您有时还会看到人们使用旧的反引号表示法,但这有 嵌套和转义方面的几个缺点:

You will sometimes also see people use the older backtick notation, but this has several drawbacks in terms of nesting and escaping:

ls > "`pwd`.txt"

注意pwd的未处理替换是绝对路径,所以上面的命令在工作目录的同一个目录下创建了一个同名的文件,但是有一个.txt 扩展.Thomas Kammeyer 指出 basename 命令去除了前导目录,因此这将在当前目录中创建一个具有该目录名称的文本文件:

Note that the unprocessed substitution of pwd is an absolute path, so the above command creates a file with the same name in the same directory as the working directory, but with a .txt extension. Thomas Kammeyer pointed out that the basename command strips the leading directory, so this would create a text file in the current directory with the name of that directory:

ls > "$(basename "$(pwd)").txt"

同时感谢erichui提出路径中空格的问题.

Also thanks to erichui for bringing up the problem of spaces in the path.

这篇关于在 bash 中使用命令的结果作为参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆