Home > Net >  Use a variable on a script command line when its value isn't set until after the script starts
Use a variable on a script command line when its value isn't set until after the script starts

Time:07-15

How to correctly pass to the script and substitute a variable that is already defined there? My script test.sh:

#!/bin/bash
   
TARGETARCH=amd64

echo $1

When i enter

bash test.sh https://example/$TARGETARCH

i want to see

https://example/amd64

but actually i see

https://example/

What am do wrong?

CodePudding user response:

The first problem with the original approach is that the $TARGETARCH is removed by your calling shell before your script is ever invoked. To prevent that, you need to use quotes:

./yourscript 'https://example.com/$TARGETARCH'

The second problem is that parameter expansions only happen in code, not in data. This is, from a security perspective, a Very Good Thing -- if data were silently treated as code it would be impossible to write secure scripts handling untrusted data -- but it does mean you need to do some more work. The easy thing, in this case, is to export your variable and use GNU envsubst, as long as your operating system provides it:

#!/bin/bash
export TARGETARCH=amd64

substitutedValue=$(envsubst <<<"$1")

echo "Original value was: $1"
echo "Substituted value is: $substitutedValue"

See the above running in an online sandbox at https://replit.com/@CharlesDuffy2/EcstaticAfraidComputeranimation#replit.nix


Note the use of yourscript instead of test.sh here -- using .sh file extensions, especially for bash scripts as opposed to sh scripts, is an antipattern; the essay at https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/ has been linked by the #bash IRC channel on this topic for over a decade.

For similar reasons, changing bash yourscript to ./yourscript lets the #!/usr/bin/env bash line select an interpreter, so you aren't repeating the "bash" name in multiple places, leading to the risk of those places getting out of sync with each other.

  • Related