Sunday 15 July 2012

Having trouble correctly passing a variable in a bash script -



Having trouble correctly passing a variable in a bash script -

i'm working on script takes flac files in format of ## artist - track.flac , pulls info file name , tags appropriately. have flags manual input of other info. problem tracknames aren't getting tagged correctly. seems it's stopping @ first white space regardless of quoting technique throws off bunch of other stuff well. you'll notice echo out trackname variable before tagging sure variable correct, is, tagging still off. help (and other pointers) in advance!

#!/bin/bash # # flac tagging script # while getopts :l:y:s:h opt ; case $opt in l) album="--set-tag=album=${optarg}" ;; y) year="--set-tag=year=${optarg}";; s) source="--set-tag=source=${optarg}" ;; h) echo >&2 "tags flac files in folder arguments: -r [artist] -l [album] -y [year] -s [source (cdr, promot, etc)]" ;; esac done shift $((optind-1)) if [ "$1" ] file if [ -e "$file" ] echo >&2 "tagging file: "$file"" filename=$(basename "$file") extension="${filename##*.}" filename="${filename%.*}" trackname="${filename##*- }" trackartist="${filename% -*}" tracknumber="${trackartist% *}" artist="${trackartist##* }" echo >&2 "$trackname" metaflac \ --set-tag=artist=$artist\ --set-tag=title=$trackname \ --set-tag=tracknumber="$tracknumber" "$album" "$year" "$source"\ "$file" else echo >&2 "no such file: "$1"" exit 1 fi done else echo >&2 "usage: "$(basename "$0")" inputfile [...]" exit 1 fi

a quick rewrite

#!/bin/bash tags=() while getopts :l:y:s:h opt; case $opt in l) tags+=( --set-tag=album="$optarg" ) ;; y) tags+=( --set-tag=year="$optarg" ) ;; s) tags+=( --set-tag=source="$optarg" ) ;; h) echo >&2 "tags flac files in folder arguments: -l [album] -y [year] -s [source (cdr, promot, etc)]" ;; esac done shift $((optind-1)) if [ $# -eq 0 ]; echo >&2 "usage: $(basename "$0") [options] inputfile [...]" exit 1 fi file; if ! [ -e "$file" ]; echo >&2 "error: no such file: $1" go on fi if ! [[ $(basename "$file") =~ ([0-9]+)" "(.+)" - "(.+)".flac"$ ]]; echo >&2 "error: can't parse filename: $file" go on fi echo >&2 "tagging file: $file" metaflac "${tags[@]}" \ --set-tag=artist="${bash_rematch[2]}" \ --set-tag=title="${bash_rematch[3]}" \ --set-tag=tracknumber="${bash_rematch[1]}" \ "$file" done

notes:

uses bash regex matching simplify (i hope) filename parsing don't nest double quotes in double qoutes: "nested" variable becomes unquoted. don't utilize all_caps_vars: 1 day you'll utilize path=/my/file , wonder why script broken

bash

No comments:

Post a Comment