Search code examples
bashfile-rename

Bash: Only one file processed with $1 but all with hard coded value


This bash code working as expected (renaming file) with the hard coded value viz. ~/Music/*.mp3. But it does not work (just processes only the first file) with files=($1) when I pass CLI argument: ./rfs.sh ~/Music/*.mp3

rfs.sh

files=(~/Music/*.mp3)

for ((i=0; i<${#files[@]}; i++)); do
    oldname="${files[$i]}"
    newname=`echo "$oldname" | sed -E 's/\/[0-9]+ /\//'`
    echo "$oldname ---> $newname"
    mv "$oldname" "$newname"
done

Solution

  • What markp-fuso said in his comment is exactly right.

    Here is how you do what you're aiming for in (remove the echo if you like the results)

    #!/bin/bash
    
    for file in "$@"; do
      dirname=${file%/*}
      basename=${file##*/}
    
       echo mv "$file ${dirname}/${basename//[[:digit:]][[:digit:]]* /}"
    done  
    

    Proof of Concept

    $ ls *.mp3
    '1234 foo.mp3'  '5678 bar.mp3'
    
    $ mp3(){ for file in "$@"; do dirname=${file%/*}; basename=${file##*/}; echo mv "$file ${dirname}/${basename//[[:digit:]][[:digit:]]* /}"; done;}; mp3 ./*.mp3
    mv ./1234 foo.mp3 ./foo.mp3
    mv ./5678 bar.mp3 ./bar.mp3