LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash: PWD minus last two directories (https://www.linuxquestions.org/questions/programming-9/bash-pwd-minus-last-two-directories-754343/)

wonderfullyrich 09-11-2009 03:02 AM

bash: PWD minus last two directories
 
I've got a script that where I'm trying to check the existance of a file two directories above the working directory. i.e. working directory is /home/bozo/ideas/thoughts and I'm interested in files in /home/bozo

How do I manipulate PWD (or something) into a variable that I can check?

I tried this but with no success.
Code:

outputfilename=bozo.mpg
outputfile=../../${outputfilename}
if [ -f ${outputfile}  ] ;

then

blah blah

else

blah blah blah


fi

I was playing pattern replacement but can't figure it out.
i.e.
Code:

${PWD##*/}
execept reversed and going back two /


TIA for any help recieved,
Rich

konsolebox 09-11-2009 04:08 AM

try
Code:

IFS=/
set -- $PWD
echo "/${*:1:$(( $# - 2 ))}"


wonderfullyrich 09-11-2009 04:42 AM

thx.
I thought a parameter subsitution would do the trick. I don't yet fully understand how this is working, but I'll keep trying to parse it.

When I tried this I'm now getting
"script.sh: 60: Bad substitution"
which is indicating the line
Code:

echo "/${*:1:$(( $# - 2 ))}"
Any idea why my script doesn't like this?

colucix 09-11-2009 05:19 AM

I'd rather return to the original issue. Why extracting this information from $PWD when the notation ../../ should work instead? Can you post the output of the following command?
Code:

bash -x script.sh
Option -x of bash let you check all the executed commands after expansions have been performed. It prints out the commands being executed, together with their output. Very useful for debugging!

The content of script.sh should be a simple test script like:
Code:

#!/bin/bash
outputfilename=bozo.mpg
outputfile=../../${outputfilename}
if [ -f ${outputfile} ]
then
  echo file found
else
  echo file not found
fi

Note that you can get the same behaviour if you put option -x in the sha-bang and run the script in the usual way.

wonderfullyrich 09-11-2009 05:32 AM

colucix, that helps a bunch. Turns out I was dumb and was missing the extension, but couldn't tell. Debug like that will be an invaluable tool!

Thanks!


All times are GMT -5. The time now is 05:45 AM.