Search code examples
bashshellquotes

Nested quotes in Bash


Please let me explain my scenario with some sample script which is much simpler than my actual application but shows the same behavior:

For the demo I use two bash shell scripts. The first one is called argtest.sh simply outputs the command line parameters:

#/bin/bash

echo "Argument 1: $1"
echo "Argument 2: $2"

Test:

root@test:~# ./argtest.sh 1 2
Argument 1: 1
Argument 2: 2

and

root@test:~# ./argtest.sh "1 2" 3
Argument 1: 1 2
Argument 2: 3

This works as expected

I've created another command like this:

./argtest.sh $(for i in ` seq 1 2 ` ; do echo Number $i; done) 

This is the result

Argument 1: Number
Argument 2: 1

I've tried many different combinations of quotation marks (") and escaped quotation marks (\") around Number, but no combination produced the desired output of:

Argument 1: Number 1
Argument 2: Number 2

How can I get to that output?


Solution

  • because arguments are subject to word splitting, you may change $IFS and put the the new separator into your echo

    IFS=$'_\n'
    ./argtest.sh $(for i in {1..2} ; do echo "Number ${i}_"; done )
    

    don't forget to restore the old $IFS

    oIFS=$IFS
    ...
    IFS=$oIFS
    

    btw {1..2} is equivalent to seq 1 2 but you don't need an external command