Search code examples
bashcd

How to use variable in bash script


user= whoami
echo $user

cd /home/${user}

I unable to change directory by this method.

output

pbsh56@pbsh56:~/Documents$ source one.sh
pbsh56

pbsh56@pbsh56:/home$ 

Solution

  • Spacing is important. Because of the space in your command, this doesn't do what you expect:

    user= whoami
    

    What that does is define an empty variable called user, and then calls the whoami command with that empty variable added to the environment. The "pbsh56" you see is from the whoami command, not from the echo.

    What you want is

    user=$(whoami)
    echo $user
    cd /home/$user