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

后端 未结 6 1112
独厮守ぢ
独厮守ぢ 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:17

    I define a short strcat function at the top of my bash script and use an inline invocation to split things up. I sometimes prefer it to using a separate variable because I can define the long literal in-line with the command invocation.

    function strcat() {
      local IFS=""
      echo -n "$*"
    }
    
    mycommand \
      --server myserver \
      --filename "$(strcat \
          extremely/long/file/name/ \
          that/i/would/like/to/be/able/to/break/ \
          up/if/possible)" \
      --otherflag \
      --anotherflag \
    

    I also like this approach for when I have to enter a long CSV of values as a flag parameter because I can use it to avoid typing the comma between values:

    function strjoin() {
      local IFS="$1"
      shift
      echo -n "$*"
    }
    
    csv_args=(
      foo=hello
      bar=world
      "this=arg  has  spaces  in  it"
    )
    mycommand \
      --server myserver \
      --csv_args "$(strjoin , "${csv_args[@]}")" \
      --otherflag \
      --anotherflag \
    

    Which is equivalent to

    mycommand \
      --server myserver \
      --csv_args "foo=hello,bar=world,this=arg  has  spaces  in  it" \
      --otherflag \
      --anotherflag \
    

提交回复
热议问题