0

Hi this is my first time writing bash and I'm trying to practice creating a bash script and am attempting to do the following:

  • Using absolute path the script changes directory to your home directory.
  • Next it verifies whether a subdirectory called project exists. If it does not exist it creates that directory.
  • Next it changes directory moving into the project subdirectory using relative path.

I'm already stuck on the first step:

#!/bin/bash
cd
if [ -d ./project ]
    then 
        echo hi it exists!
    else
        echo it doesn't exist!
cd project/

I would appreciate if someone could help! thank you so much!

Michael Albers
  • 3,721
  • 3
  • 21
  • 32
Sam
  • 495
  • 3
  • 11
  • 19
  • Do you want the script to leave the directory changed after it exits? Because you can't do that at all, which makes this entire thing moot. – Charles Duffy Oct 06 '17 at 17:59
  • If you expect to call the script and have it leave you in the target directory when it exits, then you have to source it. `. scriptName` runs it in your current context instead of a subshell. Was that what you meant to do? – Paul Hodges Oct 06 '17 at 20:28

2 Answers2

0

cd by itself changes the current working directory to the home directory. See man cd for other uses of this command.

David Harris
  • 2,332
  • 1
  • 13
  • 25
  • Since the OP is already doing that (calling `cd` by itself with no arguments -- on the second line of their script, immediately after the shebang), telling them to do what they're already doing clearly isn't an answer or solution. – Charles Duffy Oct 06 '17 at 18:05
-1

You can use the $HOME environment variable. Bash also recognizes a tilde (~) as home.

Michael Albers
  • 3,721
  • 3
  • 21
  • 32
  • This is true, but fixing that specific, narrow issue won't enable the OP to write a script that changes their shell's (that is, the calling shell's) directory. – Charles Duffy Oct 06 '17 at 18:02
  • And the OP *is* already running `cd` with no arguments at the top of their script (first line after the shebang), which *does* already change to the home directory just as effectively as `cd "$HOME"` or `cd ~` does. – Charles Duffy Oct 06 '17 at 18:04