tags:

views:

33

answers:

3

Hi Guys,

I'm having a little issue getting quite a simple bash script running.

The part that's working:

qstat -f $queuenum | grep -Po '(?<=PBS_O_WORKDIR=).*(?=,)' 

Outputs a directory to the screen (for example):

/short/h72/SiO2/defected/2-999/3-forces/FORCES_364

All I want to do is change directory to this folder. Appending a "| cd" to the end of the above command doesn't work, and I can't quite figure out how to use the $(()) tags either.

Any help would be appreciated.

+2  A: 
cd `qstat -f $queuenum | grep -Po '(?<=PBS_O_WORKDIR=).*(?=,)' `
Oli Charlesworth
yes. or equivalently or `cd $(qstat....)`
Sanjay Manohar
That's something I've tried already too. I get no errors if I attempt this, but I don't actually change directories. Do I need to escape the variable somehow for this to work?
Geodesic
@Geodesic: You can use `.` to force the script to run in the current shell, i.e. `. ./my_script.sh`.
Oli Charlesworth
Excellent. Thanks.
Geodesic
also, using double quote around the directory (`cd "$(qstat ...)"`) will work even if the directory name contains spaces.
enzotib
+1  A: 

Invoking your script creates a new bash shell

This shell is destroyed when your script ends.

If you use exec <scriptname> to run your script, the new bash shell is substituted for the current one. So if you add the command bash at the end of your script, you will get what you desire, but not the same bash shell.

Sanjay Manohar
I see. That certainly works, but isn't really the best solution. I use my history a lot so I'd prefer not to start a new shell. Any ideas on how to do that? I didn't think this issue would be a bash limitation.
Geodesic
maybe using `source scriptname` could be better, executing the script in the current shell, without substituting it.
enzotib
A: 

You should use:

cd "$(qstat -f $queuenum | grep -Po '(?<=PBS_O_WORKDIR=).*(?=,)' )"

you are trying to achieve command substitution which is achieved by using either of these two syntax:

$(command)

or like this using backticks:

`command` 

The first one is the preferred way as it allows nesting of command substitutions something like:

foo=$(command1 | command2 $(command3))

also you should enclose the entire command substitution in double quotes to protect you if the result of the command substitution is a string with spaces.

codaddict