Reputation: 739
So I have this shell script that checks and then concats an environmental variable to /etc/environment, then reloads the file without having to logout/login:
#!/bin/sh
portvar="PORT=5000"
echo $portvar
grep -q $portvar /etc/environment && echo "EV already in" || echo $portvar >> /etc/environment
set -a; source /etc/environment; set +a;
When I run it, I get the error ./test.sh: 5: ./test.sh: source: not found
. However, if I run set -a; source /etc/environment; set +a;
directly in the terminal it updates the environmental variable just fine. I have no idea what the set
command does, I just found it in another stack overflow question.
Any idea why it runs in the terminal directly but not in the .sh file? Thanks
Upvotes: 2
Views: 9173
Reputation: 58032
/bin/sh
on your system is likely some shell that isn't bash and doesn't implement the source
command. On my Ubuntu 20.04 system /bin/sh
is actually dash.
The source
command is not defined by POSIX as part of the shell command language nor is it one of the required special built-in utilities. It's a non-standard feature provided by bash
. However, the .
command, which does the same thing, is specified by POSIX.
So you can use .
instead, e.g. . /etc/environment
. Or if you want to keep using source
, then you need to have your script run by bash or some other shell that supports it, by changing the shebang line to #!/bin/bash
.
There is a tool called checkbashisms that can help you find unintentional uses of bash-specific features in your scripts. When run on your script, it flags this:
possible bashism in foo.sh line 5 (should be '.', not 'source'):
Upvotes: 4