You are not logged in.

#1 2008-03-11 15:10:44

dyscoria
Member
Registered: 2008-01-10
Posts: 1,007

Why doesn't this work in bash?

OK, just started learning how to write bash scripts, but i'm a little stumped.

touch script
chmod u+x script
vim script

And inside:

#!/bin/bash
cd $1

Running "./script /home" doesn't seem to do anything (aim here is to change directories with the script).

As I understand it, $1 will take the first argument passed when running the script. This works fine if I replace 'cd' in the script with 'echo', which will just echo back whatever argument I passed alongside. Is there something different I need to do for changing directories.


flack 2.0.6: menu-driven BASH script to easily tag FLAC files (AUR)
knock-once 1.2: BASH script to easily create/send one-time sequences for knockd (forum/AUR)

Offline

#2 2008-03-11 15:13:27

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: Why doesn't this work in bash?

When you run the script, it'll run a new instance of bash.  Inside the new instance, it'll change directories.  Then the script ends, the new instance of bash terminates, and the shell you ran the script from is back where you started.

If you use

#!/bin/bash
cd $1 
echo $(pwd)

You'll see it does actually change directories.

Offline

#3 2008-03-11 15:16:36

dyscoria
Member
Registered: 2008-01-10
Posts: 1,007

Re: Why doesn't this work in bash?

Awesome. Cheers bud!

*overcomes first hurdle*


flack 2.0.6: menu-driven BASH script to easily tag FLAC files (AUR)
knock-once 1.2: BASH script to easily create/send one-time sequences for knockd (forum/AUR)

Offline

#4 2008-03-11 15:55:38

danielsoft
Member
From: Czech Republic
Registered: 2008-02-16
Posts: 102

Re: Why doesn't this work in bash?

and there's more: if you want to run a script in the current instance of bash, use the "source" command

[danny@zdroj ~]$ cat cd-script
#!/bin/bash
cd /tmp
[danny@zdroj ~]$ ./cd-script 
[danny@zdroj ~]$ pwd                
/home/danny
[danny@zdroj ~]$ source ./cd-script 
[danny@zdroj tmp]$ pwd
/tmp
[danny@zdroj tmp]$

may the Source be with you

Offline

#5 2008-03-11 16:10:05

dyscoria
Member
Registered: 2008-01-10
Posts: 1,007

Re: Why doesn't this work in bash?

That might come in very hand actually...

Cheers!

* now understands why changes to ~/.bashrc require sourcing in ALL open xterms *


flack 2.0.6: menu-driven BASH script to easily tag FLAC files (AUR)
knock-once 1.2: BASH script to easily create/send one-time sequences for knockd (forum/AUR)

Offline

Board footer

Powered by FluxBB