質問

I have a Bash script:

src="/home/xubuntu/Documents"
mkdir -p "$src/folder1"
src="$src/folder1"

# Do something

printf "SRC IS: $src\n"
src=`cd ..` # RETURN TO PARENT DIRECTORY
printf "SRC IS: $src\n"

Basically I want to create a new folder, then do something inside the folder and after that's done I want to return to the parent directory Documents. For some reason however, src=`cd ..` returns nothing.

SRC IS: /home/xubuntu/Documents
SRC IS: 

Any ideas why?

役に立ちましたか?

解決

You can access to the parent :

src=$(cd ..&&pwd)

Much better and without using cd:

src=${src%/*} # src is the parent directory

他のヒント

cd is just to change directory, not to display it; that is done with pwd; i.e.

cd ..
src=`pwd` 

#or slightly faster
src=$PWD

what is happening is you are assigning the output from the command "cd .." to src which (as you can see when you do it on the command line) is nothing. Use readlink -f to accomplish what you need.

What you want to do instead is this:

src="/home/xubuntu/Documents"
mkdir -p "$src/folder1"
src="$src/folder1"

# Do something

printf "SRC IS: $src\n"
src=`readlink -f $src/..` # RETURN TO PARENT DIRECTORY
printf "SRC IS: $src\n"

i assume thats what you wanted to do, return the the src it's parent folder.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top