0

I am writing my own script to install my Arch Linux. I will only have few options to change every time I reinstall the system or use my script in another device. Is there a way I can write the variables at the top of my script? I came across something similar to the below but it doesn't seem to work:

disk="nvme0n1"
locale="en_US.UTF-8"

and then somewhere in the script there will be:

gdisk /dev/$disk
echo 'LANG=$locale' >> /etc/locale.conf

I can then just modify my variables at the top of my script every time I want to change something.

I am a beginner in writing scripts. I am happy if someone can explain another/better way of achieving the above.

Muzzamil
  • 3
  • 2
  • What is wrong with what you have done? You want echo 'LANG=$locale' or, better, printf '%s\n' "$locale" instead of echo 'LANG=$locale' because variables are not expanded in single quotes, but apart from that, what is the problem you are facing? How does it "not work"? – terdon Oct 10 '22 at 14:54
  • Yes, this is a good approach. You'll receive advice to write your scripts to take changeable parameters like these ones as command-line arguments. This is also good advice, but just as a child learns to crawl, then walk, then run, handling these kinds of parameters is a progression of skill and experience. Your idea is a good one for "walking". In your echo line use double quotes around the string where you want the variable expanded: echo "LANG=$locale" >> /etc/locale.conf – Sotto Voce Oct 10 '22 at 14:56
  • Essionally what I am getting when I look into my locale.conf file is: LANG=$locale instead of LANG=en_US.UTF-8

    Perhapse, I need to know what are the prerequistes for this to work. Especially when the variable is in the middle of a command like these 2 examples I gave.

    – Muzzamil Oct 10 '22 at 16:06
  • 1
    Please [edit] your question and show us: i) a script that we can run on our machines to reproduce the error, make it as simple as possible while reproducing the error; ii) the output you get from that script and iii) the output you expect. Also, please note what both earlier comments said about single quotes: you need double quotes if you want a variable expanded. So echo 'LANG=$locale' >> /etc/locale.conf will fail but echo "LANG=$locale" >> /etc/locale.conf will work. – terdon Oct 10 '22 at 16:39
  • 1
  • Other than the single quotes, the snippets in your post look fine to me. But you have $code=Input in the title, and that won't work in the shell (it'll expand $code and run the result as an argument, e.g. with code=foo, $code=Input would try to run a command called foo=Input). – ilkkachu Oct 10 '22 at 17:54
  • Thank you very much for the explanation. Yes, indeed the issue was the double quotes. I tested the commands in my question and they worked. I will apply this to my script and test it. – Muzzamil Oct 10 '22 at 19:41

0 Answers0