Search code examples
bashaudiomime

Bash: play all audio in the current directory


Here's a bash script, it

  1. gets all files in the current dir, then
  2. gets all audio files among them (allowing file-names to have whitespace)
  3. sends the list to the audacious -p - which should play the list.

The thirt step is where the script fails. Here is the script:

#!/bin/bash

find $1 -name '* *' | while read filename; do

Type=`file -i "$filename" -F "::" | sed 's/.*:: //' | sed 's/\/.*$//'`

if [ $Type=audio ]; then
    List="$List '$filename'"
fi
done

audacious2 -p $List &

So the question is: how do i convert

file name 1
file name 2
file name 3

to

'file name 1' 'file name 2' 'file name 3'

in bash?


Solution

  • #!/bin/sh
    #find "$1" -name '* *' |  # Edited as per OP's request
    find . -type f -name '* *' |
    while read -r filename; do
        case `file -i "$filename" -F "::"` in
            *::" audio"/*) echo "$filename" | tr '\012' '\000' ;;
        esac
    done |
    xargs -0 audacious2 -p &
    

    The main point here is to use xargs to feed a list of file names to a command, but I hope you will also appreciate how the pattern matching conditional is now a lot more elegant; definitely learn to use case. (I hope I got the output from file correct.)

    Edit Updated to use find -type f, read -r, tr '\012' '\000', xargs -0. By using a zero byte as a terminator, whitespace and newlines in file names are acceptable to xargs.