linux - shell 脚本 : cat configuration archive

标签 linux bash shell

现在在 bash 脚本中我有这个:

firstParam=$1
secondPara=$2
if [ -n $firstParam ] ; then 
    if [ $firstParam != "--x" ] ; then
        echo "Incorrect"
    else
       if [ -n $secondParam ]; then
           cat $secondParam
       else
           echo "Need file"
       fi    
   fi
fi

此脚本应打开配置文件并仅显示未注释的行(#、; 或/)。第一个参数也不是强制性的。 你能帮我吗?我不知道我怎么能说第一个参数不是必需的,如果你不把他也可以做​​ CAT。我的意思是您可以使用“name.sh file.conf”或“name.sh --x file.conf”执行脚本

PS:第一个参数是一个函数,如果您使用“--x file.conf”运行脚本,它将执行“cat -n”。

最佳答案

这是我通常处理争论的方式。我认为这对您来说是一个很好的基础:

XPARAM=false
OPARAM="default value"
FILENAME="/dev/stdin"

while [ $# -gt 0 ]; do
    case "$1" in
        -x|--x-long-form)
            XPARAM=true
            ;;
        -o|--option-with-arg)
            shift
            OPARAM="$1"
            ;;
        -h|--help)
            echo "usage: $0 [-x] [-o arg] FILENAME"
            exit #Don't need to do more when the user admits confusion ;-)
            ;;
        *)
            if [ "$1" == "" ]; then
                echo >&2 "I hate you"
                exit 1
            fi
            FILENAME="$1"
            ;;
    esac
    shift
done

if $XPARAM; then
    # Handle -x
fi

cat "$FILENAME"

这将选项的处理与其操作的逻辑以及它们的解释方式分开,例如是否需要或相互排斥。这也很好,因为可以将 while ... case ... shift 内容复制粘贴到一个新程序中,该程序以完全不同的方式处理其 args — 只有 case 分支需要更改。

关于linux - shell 脚本 : cat configuration archive,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16258530/

相关文章:

database - 删除包含在命令行上传递的参数的文件中的行

linux - 如何从 tcl 文件中的单个变量执行多个命令

linux - 如何阅读 npm ENOENT 错误

linux - Linux 中的 IntelliJ IDEA 编译加速

c - shell 中的历史功能

linux - 查找子目录中的所有符号链接(symbolic link)

bash - xfce-terminal 随机位置的新窗口加上回显该值

linux - 我怎样才能在 bash 脚本中打印目录树?

git - 与手动运行相比,使用 echo -n 的预提交 Hook 在 git 运行时的行为有所不同

linux - 如何在 linux 环境中的 bashrc 中包含路径