Using the result of a command as an argument in bash?

前端 未结 7 1867
野趣味
野趣味 2020-12-04 13:52

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 r

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-04 14:47

    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"
    

    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.

提交回复
热议问题