1

Sorry for this stupid question, but I spent a time to figure out!!

#! /bin/bash a=/etc cd $a

Normally, if I assign value for $a variable and then cd $a, it works. But when I create a separate file - it doesn't!

Why does it happen like this?

K7AAY
  • 16,864
  • 9
  • 45
  • 77
J. Doe
  • 105
  • 10
  • 3
    It probably *does* work - but not in the way that you imagine. See [Why doesn't “cd” work in a shell script?](https://askubuntu.com/questions/481715/why-doesnt-cd-work-in-a-shell-script) – steeldriver May 06 '20 at 20:58
  • @k7aay Please do not add Ubuntu version to title (especially) when the version is not important to the question at all. – pomsky May 07 '20 at 12:13

1 Answers1

4

You're executing your script using #!/bin/bash which launches the new bash session invisible for you and changes its directory to $a and then exits. You just don't see it.

To achieve what you want, I've slightly modified your script:

$ cat test.sh
#!/bin/bash
a="/etc/"
cd $a
echo $a

$ chmod +x test.sh

And executed it using a . dot before script (or source keyword). It executes script inside of the current bash session:

Result:

user@ubuntu:~/test$ . test.sh 
/etc/
user@ubuntu:/etc$ 
Gryu
  • 7,279
  • 9
  • 31
  • 52