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

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

问题描述

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

  ls > list.txt 

我想使用 pwd 打印工作目录)命令。



类似:

  ls> $ {pwd} .txt 

这不起作用 - 任何人都可以告诉我我需要什么语法

编辑:如同在注释中提到的,pwd将最终给出一个绝对路径,所以我的播放列表将最终在某个目录中被命名为.txt - d!所以我必须修剪路径。感谢您发现 - 我可能已经花了很多时间想知道我的文件在哪里了!

解决方案

使用反引号替换命令:

  ls> `pwd`.txt

如Landon指出, $ cmd)等效:

  ls> $(pwd).txt

请注意,未处理的替换 pwd 是一个绝对路径,因此上述命令在与工作目录相同的目录中创建一个具有相同名称的文件,但使用 .txt 延期。 Thomas Kammeyer指出, basename 命令会删除主目录,因此将在当前目录中创建一个包含该目录名称的文本文件:

  ls> `basename$(pwd)`.txt

还要感谢erichui路径中的空格问题。


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

ls > list.txt

I would like to use the result of the pwd (print working directory) command for the name of the playlist.

Something like:

ls > ${pwd}.txt

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

Edit: 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!

解决方案

Use backticks to substitute the result of a command:

ls > "`pwd`.txt"

As pointed out by Landon, $(cmd) is equivalent:

ls > "$(pwd).txt"

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"

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

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

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