Home > Software engineering >  how list just one file from a (bash) shell directory listing
how list just one file from a (bash) shell directory listing

Time:12-02

A bit lowly a query but here goes: bash shell script. POSIX, Mint 21

I just want one/any (mp3) file from a directory. As a sample. In normal execution, a full run, the code would be such

for f in *.mp3 do
  #statements
done

This works fine but if I wanted to sample just one file of such an array/glob (?) without looping, how might I do that? I don't care which file, just that it is an mp3 from the directory I am working in. Should I just start this for-loop and then exit(break) after one statement, or is there a neater way more tailored-for-the-job way?

for f in *.mp3 do
  #statement
  break
done

Ta (can not believe how dopey I feel asking this one, my forehead will hurt when I see the answers )

CodePudding user response:

I would do it like this in POSIX shell:

mp3file=
for f in *.mp3; do
    if [ -f "$f" ]; then
        mp3file=$f
        break
    fi
done
# At this point, the variable mp3file contains a filename which
# represents a regular file (or a symbolic link) with the .mp3
# extension, or empty string if there is no such a file.

CodePudding user response:

The fact that you use

for f in *.mp3 do

suggests to me, that the MP3s are named without to much strange characters in the filename.

In that case, if you really don't care which MP3, you could:

f=$(ls *.mp3|head)
statement

Or, if you want a different one every time:

f=$(ls *.mp3|sort -R | tail -1)

Note: if your filenames get more complicated (including spaces or other special characters), this will not work anymore.

  • Related