How to print a string with a variable by using the echo command in the shell script All In One
Node.js &
nvm
question
I defined a shell variable in the terminal and then used the echo command to output a string with that variable and it worked fine in the terminal.
But when I use the same command in a shell script, the variable disappears without any output or error.
So, what's going on.
terminal
$ NVM_USER=xgqfrms
$ echo $NVM_USER
xgqfrms
$ echo "string with a variable $NVM_USER"
string with a variable xgqfrms
$ echo string with a variable $NVM_USER
string with a variable xgqfrms
$ echo "string with a variable ${NVM_USER}"
string with a variable xgqfrms
shell script
#!/usr/bin/env bash
echo $NVM_USER
echo "string with a variable $NVM_USER"
echo string with a variable $NVM_USER
echo "string with a variable ${NVM_USER}"
I've searched and tried some solutions but still stuck.
update
It works using a variable defined in shell scripts.
#!/usr/bin/env bash
user=xgqfrms
echo "string with a variable ${user}"
# temp=$(echo $NVM_USER)
echo "string with a variable ${temp}"
solutions
1. when using the same terminal
# terminal
$ export NVM_USER=xgqfrms
$ ./test.sh
As answered by Gilles Quénot
2. when using different terminals
bash
demo
# terminal 1
# 1. add your export variable to the shell config file
$ sudo vim .bashrc
export NVM_USER=xgqfrms
# fresh the config
$ source ~/.bashrc
# terminal 2
$ ./test.sh
zsh
demo
# terminal 1
# 1. add your export variable to the shell config file
$ sudo vim .zshrc
export NVM_USER=xgqfrms
# fresh the config
$ source ~/.zshrc