-1

I am deploying my shell script to a CI pipeline, there are three different environment variables defined on CI: $prod, $dev, $test.

My script managed to return the correct string value based on deployment type:

#!/bin/sh

my_env = // the checking logic

the value of my_env is a string value of one of 'prod', 'dev' or 'test'

I wonder how can I make a variable out of my_env to point to the value to either $prod or $dev or $test dynamically now in my script? I mean I can't $my_env since it only hold the string value e.g. dev instead of the actual value of $dev.

ilkkachu
  • 138,973

1 Answers1

-1

You can't: That's not how variables work.

But you can replace variables wherever you use them with calls to shell functions. That's easy, but it depends on what shell you use; sadly, your symbolic /bin/shell doesn't tell us!

For zsh, something like

check_env() {
   # do your checking
   print "prod"  # or "test" or whatever
}

...

if [[ "$(check_env)" = "prod" ]] { rm -rf / }

  • How to tell what shell do I use in script? Do you mean there is another more specific header than #!/bin/shell? Could you please make an example for that? – user842225 Mar 07 '22 at 10:27
  • 1
    I've never seen a /bin/shell on a linux system, I don't know where you have that from. So, I don't know what to tell you! – Marcus Müller Mar 07 '22 at 10:32
  • 2
    I think you need to read What the first line in your script means; honestly, you doing CI without knowing this is not great! – Marcus Müller Mar 07 '22 at 10:34
  • In general, "you can't" is wrong. For many shells in common use, it's quite possible (easy even in Bash, ksh and zsh, and doable with eval in any standard shell). – ilkkachu Mar 07 '22 at 21:28
  • @ilkkachu but calling eval instead of a function is not easier; sure, I can expand a variable twice... but that would require me to formulate the check as variable expn expression, somehow. – Marcus Müller Mar 07 '22 at 21:33
  • I'm also not exactly sure what the check_env function is supposed to do here, or if it in fact works. print("prod") looks like it's treated as a glob (with the flags p, r and od), and it probably gives an error for a non-matching pattern – ilkkachu Mar 07 '22 at 21:34
  • @ilkkachu thanks for spotting that; the parens are wrong, of course. check_env just contains exactly the checks that OP alludes to in their // the checking logic; the print is just an example "result" of that, illustrating how the information is passed from the function to the rest of the program logic – Marcus Müller Mar 07 '22 at 21:35
  • @user842225 The pathname following the shebang is treated as the interpreter of the script. Simply do ls -l /bin/shell (or whatever else you have, odds are it's actually /bin/sh) to check. You can also file /bin/sh if you have file(1) installed. – Vilinkameni Mar 09 '22 at 08:30