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

2018-07-24  本文已影响188人  VictorZhangWang

新建的脚本,指定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
上一篇下一篇

猜你喜欢

热点阅读