Search code examples
linuxbashshelliols

bash - redirect ls into custom script


For college I am writting a script to read and display id3 tags in mp3 files. The arguments would be the files i.e

./id3.sh file1.mp3 file2.mp3 morefiles.mp3

I can read the arguments using $0, $1 etc. and get the number of args with $#. how can I get it to read the output from a ls command?

ls *.mp3 | ./id3.sh

Solution

  • I would suggest using pipe and xargs with -n argument, in the example below the id3.sh script will be called with at most 10 files listed by ls *.mp3. This is very important, especially if you can have hounreds or thousands of files in the list. If you omit the -n 10 then your script will be called only once with the whole list. If the list is too long your system may refuse to run your script. You can experiment how much files in each invokation of your script to process (e.g. what is more efficient in your case).

    ls *.mp3 | xargs -n 10 id3.sh
    

    then you can read the files in your id3.sh script like this

    while [ "$1" != "" ]; do
        #next file available in ${1}
        shift
    done