美文网首页
Shell-新建的shell 脚本传入带有空格的参数

Shell-新建的shell 脚本传入带有空格的参数

作者: VictorZhangWang | 来源:发表于2018-07-24 13:11 被阅读188次

    新建的脚本,指定APP打开文件

    #!/bin/sh
    
    printHelpDoc()
    {
        printf "Usage: ./OpenFile.sh [-a <application>] [filenames] [--args arguments]\n"
        printf "Help: Open opens files from a shell.\n\tBy default, opens each file using the default application for that file. \n\tIf the file is in the form of a URL, the file will be opened as a URL.\n"
        printf "Options:\n"
        printf "\t-a      Opens with the specified application.\n\n\n"
    }
    #params count
    paramCount=$#
    printf "paramCount=$paramCount\n"
    
    #是否包含第1个参数
    if [ -z "$1" ]; then
        printf "Please enter the valid arguments\n"
        #printHelpDoc
        exit 1
    elif  test $1 = "-a" 
     then
        if [ -z "$2" ]; then
            printf "Please enter the valid arguments\n"
            exit 1
        fi
    fi
    
    
    for (( i = 1; i <= paramCount; i++ )); do
        #statements
        params[i-1]="${!i}"
        echo ${params[i-1]}
    done
    
    firstArg="${params[0]}"
    secondArg="${params[1]}"
    index=0
    if test $firstArg = "-a" ; then
        let index=2
    fi
    
    if [ $index -eq $paramCount ]; then
        printf "open $firstArg $secondArg\n"
        open "$firstArg" "$secondArg"
        else
              for (( i = index; i < paramCount; i++ )); do
                  #statements
                  arg="${params[i]}"
                  if test $firstArg = "-a" ; then
                      printf "$i open $firstArg $secondArg $arg\n"
                      open "$firstArg" "$secondArg" "$arg"
                  else
                      open "$arg"
                  fi
              done
    fi
    
    

    执行过程中,发现带空格的参数总是不对,后来在脚本中取参数时都加上"",问题解决


    image.png

    相关文章

      网友评论

          本文标题:Shell-新建的shell 脚本传入带有空格的参数

          本文链接:https://www.haomeiwen.com/subject/pyvemftx.html