How can I change a folder path in a shell script variable?

September 5, 2025 4 answers
Asked by CuriousCat42
Hey everyone! I've run into a bit of a conundrum with manipulating folder paths in my shell script. I have environment variables that hold paths, for example, `/var/log/somefolder/somefolder2`. What I need to do is set a new path that goes two directories up, ending up with `/var/log`. The actual paths I'm working with are dynamic, but for now, let's say they look like the one above. I've tried appending `../` to the end of my path, which gives me something like `/var/log/somefolder/somefolder2/../../`. It works with some commands but not all. Is there a straightforward way to programmatically get the parent folder a certain number of levels up? I know `dirname` can help get the base directory, but would running it multiple times be the best route, or is there a simpler solution?

Answers

ScriptNinja77
You could try something like this: ```bash nn=2 PATH="/var/log/a/b" DIR=$(cut -d'/' -f-$((nn + 1)) <<< "$PATH") ``` This should give you the desired result of `/var/log`.
Reply to this answer
PathExplorer93
Iโ€™ve actually used `realdir` or `realpath`, and it worked wonders for me. I wouldโ€™ve shared earlier, but I thought my previous post got removed right after I posted it. Thanks for all the input, though!

ShellSavant: Usually, I pipe it through `dirname` with proper quotingโ€”especially for paths that include spaces. There are also some IFS tricks you can use if required. Iโ€™ll need to check out `realpath`; never heard of that one!

Reply to this answer
PathFinder21
You could also simplify by just navigating up two directories like this: ```bash cd $VARPATH && cd .. && cd .. ``` Alternatively, you could set two variables: ```bash PATH1="/var/log" PATH2="dir1/dir2" ``` Then concatenate them when you need the full path, or just use the first variable when you need the partial path. Easy as pie!
Reply to this answer
HelpfulHank
You might find the `find` command useful! For instance: ```bash $ export DIR=$(find "/var" -type d -iname "log" | head -1) $ path="${DIR}/somefolder" ``` Also, if you know thereโ€™s a hidden file in the directory, you could touch it: ```bash $ touch /var/.findmydir $ export DIR=$(find "/var" -type f -iname ".findmydir") ``` If you're writing a script, a simple built-in might work too: ```bash DIR=${0%/*} # This gets the path to the last / ``` And you can also use: ```bash DIR="$(dirname "$(readlink -f "${0%/*}")")" ``` Hope one of these helps! It's really up to how you want to structure your commands.
Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions