Bash: space in variable value later used as parameter

前端 未结 4 2022
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-18 03:52

While writing a bash script to help creating polaroid thumbnail using Imagick\'s convert commmand. I encounter a problem. Although, I manage to work around with

4条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-18 04:54

    Use an array, as so:

    #!/bin/bash
    # ^^^ - note the shebang line explicitly using bash, not /bin/sh
    
    CAPTION="Is this Cute?" # The actual value will be tacked from the parameter of this bash.
    IN_FILE="resources/puppy.png"
    OUTFILE="resources/puppy_polaroid.png"
    
    extra_args=( )
    if [[ $CAPTION ]] ; then
      extra_args+=( -caption "$1" )
    fi
    convert "${extra_args[@]}" "$INFILE" "$OUTFILE"
    

    This construct presumes that you're potentially going to be appending numerous extra arguments. Note that += is unsupported in some older versions of bash which are still present on systems deployed in the field (most notably RHEL4). For such older releases it can be necessary to write extra_args=( "${extra_args[@]}" -caption "$1" ) to append to an array.

提交回复
热议问题