Mike Thrussell
Mike Thrussell

Reputation: 4515

print multiple lines in shell - improving readability in provisioning a Vagrantfile

I use printf to setup my Nginx settings, and it works fine, but it's awkward to read and alter; is there a better way to improve readability?

config.vm.provision "shell", inline: <<-SHELL

    sudo rm /etc/nginx/sites-enabled/default

    sudo printf '%s\n' 'server {' 'root /home/vagrant/web;' 'index index.php index.html index.htm;' 'location / {' 'try_files $uri $uri/ /index.php?$args ;' '}' 'location ~ \.php$ {' 'fastcgi_split_path_info ^(.+\.php)(/.+)$;' 'fastcgi_pass unix:/var/run/php5-fpm.sock;' 'fastcgi_index index.php;' 'include fastcgi_params;' '}' '}' >> /etc/nginx/sites-enabled/default

    sudo service nginx start

SHELL

Upvotes: 3

Views: 4666

Answers (1)

Ivan Tsirulev
Ivan Tsirulev

Reputation: 2811

Assuming that there is Bash on your guest machine, you could try and use nested bash here documents. There is no guarantee that will work with Vagrantfile but it's worth a shot anyway.

config.vm.provision "shell", inline: <<-SHELL

    sudo /bin/bash << 'SCRIPT'
        rm /etc/nginx/sites-enabled/default;

        cat << 'EOF' >> /etc/nginx/sites-enabled/default
            %s\n

            server {
                root /home/vagrant/web;
                index index.php index.html index.htm;

                location / {
                    try_files $uri $uri/ /index.php?$args ;
                }

                location ~ \.php$ {
                    fastcgi_split_path_info ^(.+\.php)(/.+)$;
                    fastcgi_pass unix:/var/run/php5-fpm.sock;
                    fastcgi_index index.php;
                    include fastcgi_params;
                }
            }
EOF
        service nginx start
SCRIPT
SHELL

Note that EOF, SCRIPT and SHELL must be placed in the very beginning of the line. There must not be any tabs or whitespaces in front of these words.

Upvotes: 4

Related Questions