简体   繁体   中英

Bash cd .. returns nothing

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; ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM