How do I break up an extremely long string literal in bash?

后端 未结 6 1118
独厮守ぢ
独厮守ぢ 2021-01-30 10:21

I would like to embed a long command like this in a bash script:

mycommand \\
    --server myserver \\
    --filename extremely/long/file/name/that/i/would/like/         


        
6条回答
  •  长发绾君心
    2021-01-30 11:02

    Another way of writing a long string to a variable while keeping the maximum line length at bay:

    printf -v fname '%s' \
        'extremely/long/file/name/that/i/' \
        'would/like/to/be/able/to/break/up/' \
        'if/possible'
    

    Because there are more arguments than formatting directives, %s is just repeated and we get

    $ declare -p fname
    declare -- fname="extremely/long/file/name/that/i/would/like/to/be/able/to/break/up/if/possible"
    

    which an be used like

    mycommand \
        --server myserver \
        --filename "$fname" \
        --otherflag \
        --anotherflag
    

    This is extra handy when setting long variables with inherently separated contents such as CDPATH (or PATH, of course):

    printf -v CDPATH '%s' \
        ':/Users/benjamin/here/is/a/long/path' \
        ':/Users/benjamin/and/here/is/another/one' \
        ':/Users/benjamin/and/a/third/line'
    export CDPATH
    

    as opposed to

    export CDPATH=':/Users/benjamin/here/is/a/long/path:/Users/benjamin/and/here/is/another/one:/Users/benjamin/and/a/third/line'
    

    or the clunky

    export CDPATH=':/Users/benjamin/here/is/a/long/path'
    CDPATH+=':/Users/benjamin/and/here/is/another/one'
    CDPATH+=':/Users/benjamin/and/a/third/line'
    

提交回复
热议问题