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

0
22
Asked By CuriousCat42 On

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?

4 Answers

Answered By HelpfulHank On

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.

Answered By PathFinder21 On

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!

Answered By PathExplorer93 On

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!

Answered By ScriptNinja77 On

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`.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.