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

前端 未结 7 1826
野趣味
野趣味 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:28

    to strip all but the directory name

    ls >/playlistdir/${PWD##/*}.txt
    

    this is probably not what you want because then you don't know where the files are (unless you change the ls command)

    to replace "/" with "_"

    ls >/playlistdir/${PWD//\//_}.txt
    

    but then the playlist would look ugly and maybe not even fit in the selection window

    So this will give you both a short readable name and usable paths inside the file

    ext=.mp3 #leave blank for all files
    for FILE in "$PWD/*$ext"; do echo "$FILE";done >/playlistdir/${PWD##/*}.txt
    
    0 讨论(0)
  • 2020-12-04 14:34

    The syntax is:

    ls > `pwd`.txt
    

    That is the '`' character up underneath the '~', not the regular single quote.

    0 讨论(0)
  • 2020-12-04 14:37

    This is equivalent to the backtick solution:

    ls > $(pwd).txt
    
    0 讨论(0)
  • 2020-12-04 14:42

    I suspect the problem may be that there are spaces in one of the directory names. For example, if your working directory is "/home/user/music/artist name". Bash will be confused thinking that you are trying to redirect to /home/user/music/artist and name.txt. You can fix this with double quotes

    ls > "$(pwd).txt"
    

    Also, you may not want to redirect to $(pwd).txt. In the example above, you would be redirecting the output to the file "/home/user/music/artist name.txt"

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-04 14:49

    Using the above method will create the files one level above your current directory. If you want the play lists to all go to one directory you'd need to do something like:

    #!/bin/sh
    
    MYVAR=`pwd | sed "s|/|_|g"`
    ls > /playlistdir/$MYVAR-list.txt
    
    0 讨论(0)
提交回复
热议问题