Register
It is currently Sat Nov 01, 2014 7:14 am

global variable


All times are UTC - 6 hours


Post new topic Reply to topic  [ 3 posts ] 
Author Message
 PostPosted: Sat Jul 10, 2010 6:07 pm   

Joined: Fri Jul 09, 2010 6:53 pm
Posts: 5
This is what I have for my cd command: echo "going from $PWD to $1"; cd $1;

Everything works except it doesn't change directories.

This is what I have for my go_back command: echo "going back to $OLDPWD"; cd ~-;

But this is what happens when I run it:

going back to
./go_back: line 1: cd~-: command not found

So I emailed my teacher and this is what he said:


What's going on is, your executing the shell script inside new session instead of the current session.

try putting:

#!/bin/bash

as the first line in your script. This will force it to execute it in the current session. To go back, set up a Global Variable which will hold your past directory, store that directory in the Global Variable before you change directories, in your go_back, just cd to your Global Variable.

I read about global variables and I know how to make them, but I don't really have any experience with them, so I am just a little confused on how to use a global variable to make my two scripts work.


Top
 Profile  
 PostPosted: Sat Jul 10, 2010 7:59 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 552
hey,

Quote:
./go_back: line 1: cd~-: command not found

there must be a space between cd and ~-


I don't know how works putty; and I don't know what "global variables" are (except against local ones in functions).
Bash has some variables that it creates, such as BASH_VERSION, SHELLOPTS, PWD, and so on.

A script always runs in a subshell, it will never change the directory of the main shell.
A script is a child process, it can't change any variable of its parent.

try to add some pwd commands into your script, you'll see it changed directory.
it's the same as
Code:
var="foo"; echo "mainshell pwd is $(pwd), and var = \"$var\""; (echo "subshell pwd is $(pwd), and var = \"$var\""; echo "changing directory, and var's value"; cd /bin; var="bar"; echo "subshell pwd is now $(pwd), and var = \"$var\""); echo "mainshell pwd is still $(pwd), and var = \"$var\""
typed on the command line: what's between '(' and ')' is executed in a subshell.


Top
 Profile  
 PostPosted: Wed Jul 14, 2010 10:28 am   

Joined: Fri Jul 09, 2010 6:53 pm
Posts: 5
Thank you for the help!


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 3 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 5 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
cron


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP