通过文件扩展名验证脚本的参数?

时间:2012-10-09 12:11:31

标签: linux validation shell arguments

我正在编写一个脚本,您可以将文件名作为参数传递,只有当它是某个文件扩展名时才会运行。

flac2mp3 "01 Song.flac"

flac2mp3 "01 Song.FLAC"

我知道有很多脚本向你展示如何将flac转换为mp3,但这是我的脚本,我想学习如何使用这种方法编写脚本。

这样我就可以学习参数,以及何时只想转换1个单独的文件。 (对于多个文件,我只是在脚本中用* .flac写了一个for循环)

我只是想学习如何检查$ 1参数是否包含*。[Ff] [Ll] [Aa] [Cc]

这是我到目前为止从互联网拼凑起来的东西(我知道这是一个令人尴尬的错误,但我想展示我的目的):

#!/bin/bash
#flac2mp3

if [ -z $1 ] && [[$1 !=~ *.[Ff][Ll][Aa][Cc]]];then echo "Give FLAC File Name"; exit 0;fi

OUTF=${1%.flac}.mp3

ARTIST=$(metaflac "$1" --show-tag=ARTIST | sed s/.*=//g)
TITLE=$(metaflac "$1" --show-tag=TITLE | sed s/.*=//g)
ALBUM=$(metaflac "$1" --show-tag=ALBUM | sed s/.*=//g)
GENRE=$(metaflac "$1" --show-tag=GENRE | sed s/.*=//g)
TRACKNUMBER=$(metaflac "$1" --show-tag=TRACKNUMBER | sed s/.*=//g)
DATE=$(metaflac "$1" --show-tag=DATE | sed s/.*=//g)

flac -c -d "$1" | lame -m j -q 0 --vbr-new -V 0 -s 44.1 - "$OUTF"
id3 -t "$TITLE" -T "${TRACKNUMBER:-0}" -a "$ARTIST" -A "$ALBUM" -y "$DATE" -g "${GENRE:-12}" "$OUTF"

done

请感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

请尝试以下代码:

shopt -s nocasematch

if [[ $1 == *flac ]]; then
    echo "ok"
fi

这不区分大小写。

修改

$ LANG=C help shopt
shopt: shopt [-pqsu] [-o] [optname ...]
    Set and unset shell options.

    Change the setting of each shell option OPTNAME.  Without any option
    arguments, list all shell options with an indication of whether or not each
    is set.

    Options:
      -o        restrict OPTNAMEs to those defined for use with `set -o'
      -p        print each shell option with an indication of its status
      -q        suppress output
      -s        enable (set) each OPTNAME
      -u        disable (unset) each OPTNAME

    Exit Status:
    Returns success if OPTNAME is enabled; fails if an invalid option is
    given or OPTNAME is disabled.

如果您在shell中单独运行shopt,您将看到可用的选项:

$ shopt
autocd          on
cdable_vars     on
cdspell         off
checkhash       off
checkjobs       off
checkwinsize    off
cmdhist         on
compat31        off
compat32        off
compat40        off
compat41        off
direxpand       off
dirspell        off
dotglob         on
execfail        off
expand_aliases  on
extdebug        off
extglob         on
extquote        on
failglob        off
force_fignore   on
globstar        on
gnu_errfmt      off
histappend      on
histreedit      off
histverify      off
hostcomplete    off
huponexit       off
interactive_comments    on
lastpipe        off
lithist         off
login_shell     off
mailwarn        off
no_empty_cmd_completion off
nocaseglob      off
nocasematch     off
nullglob        off
progcomp        on
promptvars      on
restricted_shell        off
shift_verbose   off
sourcepath      on
xpg_echo        off

要知道所有这些选项是什么:

man bash | less +/'^SHELL BUILTIN COMMANDS'

然后在本节内搜索`shopt。