1

I have to write a shell script to install multiple services dynamically. I don´t know too much about shell scripting or the unix shell general, so I really need some help. This is my shell file.

#!/bin/bash
# Ask the user for their name
echo What is the name of your domain?
read varname

echo You passed the domain name to your domain $varname successfully

This is my nginx.conf file.

server {
  listen                80;
  server_name           $varname;
  rewrite     ^(.*)     https://$server_name$1 permanent;
}

I want to pass varname to the nginx.conf file to set the server name based on the users input. How can I do this?

3 Answers 3

1

You could create the file nginx.conf from a heredoc.

#!/bin/bash
# Ask the user for their name
echo What is the name of your domain?
read varname

cat > nginx.conf <<EOF
server {
  listen                80;
  server_name           $varname;
  rewrite     ^(.*)     https://\$server_name\$1 permanent;
}
EOF

echo You passed the domain name to your domain $varname successfully

Note: In the rewrite line I escaped the $ characters to get literal $ in the output instead of shell variable expansion.

If I enter foobar, this results in a file nginx.conflike this:

server {
  listen                80;
  server_name           foobar;
  rewrite     ^(.*)     https://$server_name$1 permanent;
}
Sign up to request clarification or add additional context in comments.

Comments

1

Could you please try following. This will change value on line which is starting from space and has server_name's last field to provided value by user.

#!/bin/bash
# Ask the user for their name
echo What is the name of your domain?
read varname

awk -v var="$varname" '/^ +server_name/{$NF=var} 1' nginx.conf > temp && mv temp nginx.conf &&\
echo You passed the domain name to your domain $varname successfully

Comments

1

You can use envsubst for this.

Rename your nginx.conf to nginx.conf.template and change your script to:

#!/bin/bash

read -p "What is the name of your domain? " varname

export varname
envsubst '$varname' < nginx.conf.template > nginx.conf

echo "You passed the domain name to your domain $varname successfully"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.