Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to go 1 level back for a directory path stored in a variable

Tags:

path

go

I'm trying to go back 1 level back in a stored variable in Go Lang, how could I do this?

Origin:
"/root/path"

Expected:
"/root/"

There's a function that could do that automatically? or I have to do it manually?

Thanks.

like image 940
Javier Salas Avatar asked Jul 09 '18 22:07

Javier Salas


People also ask

How do I go back a file path?

Starting with “/” returns to the root directory and starts there. Starting with “../” moves one directory backwards and starts there. Starting with “../../” moves two directories backwards and starts there (and so on…) To move forward, just start with the first subdirectory and keep moving forward.

How do I go back one directory in a shell script?

The .. means “the parent directory” of your current directory, so you can use cd .. to go back (or up) one directory. cd ~ (the tilde). The ~ means the home directory, so this command will always change back to your home directory (the default directory in which the Terminal opens).

How do I go back one directory in Perl?

use strict; use warnings; use Cwd qw(); my $path = Cwd::cwd(); print "Debug : $path\n"; From the above code i can get the current working directory but need to go back one level down. Do you want the current directory, or the directory your script resides in?

How to go back one directory in Git Bash?

To navigate up one directory level, use "cd.." To navigate to the previous directory (or back), use "cd -" To navigate into the root directory, use "cd /" Add a Grepper Answer Javascript answers related to “how to go back one directory in git bash”

How do I CD to the previous directory in Linux?

To cd to the previous directory, you can use one of the following commands in bash: cd - cd "$OLDPWD" To cd to your home directory, use one of: cd cd ~ cd "$HOME"

How do I get to the home directory?

If you want to go to home dir specifically, use cd, cd $HOME, or cd ~. Show activity on this post. cd ~ will work. ~ is basically a shortcut for /home/user.


1 Answers

The parent directory can always be referred to by .., so you can append that to your path.

For example:

p := "/root/path/"
p = filepath.Clean(filepath.Join(p, ".."))
fmt.Println(p)
// "/root"

If path is not a directory itself (or you are certain that it will not end in a path separator), then you can use the Dir function to get the containing directory. Dir returns all but the last element of path, typically the path's directory:

p := "/root/path"
p = filepath.Dir(p)
fmt.Println(p)
// "/root"
like image 160
JimB Avatar answered Sep 27 '22 23:09

JimB