Issue
I'm setting up a script that uses variables from another script.
Script 1 has the variables
Script 2 sources script 1 and output an unexpected error.
Fresh Debian 9 install via GCP.
1.sh
1="test"
2="test2"
3="test3"
2.sh
source 1.sh
echo $1
echo $2
echo $3
Running 2.sh, I expected:
test
test2
test3
But I received:
1.sh: line 2: 1=test: command not found
1.sh: line 3: 2=test2: command not found
1.sh: line 4: 3=test3: command not found
#empty line#
#empty line#
#empty line#
This link is telling me that's how a bash variable is declared.
How do I solve this problem?
Solution
1
, 2
, and 3
are not valid variable names. $1
etc are used to access the arguments passed to a script, but they cannot be assigned to like normal variables. Try using something like var1="test"
etc instead.
Also, I recommend adding a shebang line (e.g. #!/bin/bash
or #!/usr/bin/env bash
) to the beginning of 2.sh. It doesn't matter for 1.sh, since source
ing a script doesn't pay attention to shebang lines.
Oh, and I forgot another thing: when you use a variable (or parameter, or whatever), you should almost always put double-quotes around it (e.g. use echo "$var1"
instead of just echo $var1
). When you use a variable without double-quotes, the shell will try to parse it in ways that are more likely to cause trouble than to help.
And finally: especially when you're starting out, try pasting your scripts into shellcheck.net -- it's good at spotting common scripting mistakes, and can point them out before they become bad habbits.
Answered By - Gordon Davisson