0

I'm now writing bash script to get project directory in my project. Following is my folder structure. When I go api folder and type pwd, I will get "/Users/ppshein/Documents/projects/api" but what I want is I want to get "/Users/ppshein/Documents/projects/my-layers" from api folder.

├── README.md
├── api
├── node_modules
├── package.json
├── report
├── serverless.yml
├── webpack.config.js
└── my-layers

Is there anyway we can do in bash script?

PPShein
  • 13,309
  • 42
  • 142
  • 227
  • 2
    `$(pwd)/../my-layers` ? – armnotstrong May 20 '20 at 07:09
  • @armnotstrong it does not work. – PPShein May 20 '20 at 07:33
  • 1
    @PPShein what exactly did not work about it? Also, see [How do I navigate up one directory?](https://askubuntu.com/questions/703698/how-do-i-navigate-up-one-directory-from-the-terminal). – Socowi May 20 '20 at 07:44
  • 1
    @PPShein : If you don't want to invoke `pwd`, you could also do a `other_dir="$PWD/../my-layers"`. If you don't want to see the `..` inside the path, and have `readlink` installed, do a `other_dir=$(readlink -f ../my-layers)`. If you don't have `readlink`, you maybe have `realpath`. In this case, it would be `other_dir=$(realpath ../my-layers)`. – user1934428 May 20 '20 at 08:16
  • duplicates: [get parent directory of a file in bash](https://stackoverflow.com/q/40700119/995714), [Get the parent directory of a given file](https://unix.stackexchange.com/q/351916/44425), [Getting the parent of a directory in Bash](https://stackoverflow.com/q/8426058/995714) – phuclv Mar 20 '21 at 01:21

2 Answers2

1

You can get the parent directory like so:

parent="$(dirname "$(pwd)")"

Then

"${parent}/my-layers"

See Getting the parent of a directory in Bash for more details about how you can get the parent directory

gohu
  • 151
  • 1
  • 9
1

I prefer to use this trick

BASE_DIR=$(dirname $(readlink -m $0))

this will get the dir that contains your script with variable ${BASE_DIR}. normally, it's the root dir of your project, or at least you could find something to work with. ../ something like that.

The good news is that it doesn't use a command like pwd which maybe environment-related. So that you could execute your script anywhere you like, especially useful in a crontab.

armnotstrong
  • 8,605
  • 16
  • 65
  • 130