0

I'm trying to change directory in shell script to the one given by the command line argument.

#!/bin/bash
chmod 755 findfn.sh
dir=$1

while [ -d "${dir}" ]
do
    cd $HOME/"$1"
done

I've looked at many other posts and tried:

  • cd "dir"
  • cd ~/"$1"
  • cd source "$1"
  • Removing #!bin/bash
  • Changing chmod 755 to chmod 700, etc

Where am I going wrong?

EDIT Just tried this

alias dirc="cd /home/$1"
    echo $PWD

but it still doesnt change directory, it just keeps printing out "/home"

ian
  • 33
  • 5
  • (why do you use for loop?) do you wish you could cd to that dir after you execute the file? but script is running in subshell, after your program exit, it will still be in the original dir – ZNZNZ Mar 29 '18 at 02:57
  • Yes the reason why I'm using while is because I am going to add in more commands later, after I figure out how to cd first – ian Mar 29 '18 at 03:01
  • 2
    you add `echo $PWD` under your `cd` command, and see whether the dir already changed? – ZNZNZ Mar 29 '18 at 03:03
  • 2
    changing present working directory is specific to that process. Check this post, if you really want to change your shell $PWD [https://stackoverflow.com/questions/874452/change-the-current-directory-from-a-bash-script] (Change the current directory from a Bash script) – Ravi Mar 29 '18 at 03:21
  • @ian : Do a `pwd` right after the `cd`, for verifying. Of course if `$1` contains a nonsense value, the command might fail, but you would then see an error message. If you want to be on the safe side, you can also check the status code after cd. If `cd` does not work, `$?` is non-zero. – user1934428 Mar 29 '18 at 06:09
  • How many times do you think `while [ -d "${dir}" ]` will execute if `$dir` is never updated? Do you expect to be left in the new directory when the script exits? What is the value of `$PWD` in the parent shell before you execute the child script? What is the rule about a child being able to affect the environment of its parent? – David C. Rankin Mar 29 '18 at 06:41

1 Answers1

0
$ cat a.sh
#!/bin/bash
dir=$1

while [ -d "${dir}" ]  #it will check if the argument directory is present where script is executed.
do
    cd $HOME/"$1"  
done

Let's say /tmp contains above script as a.sh, and /tmp/abc is present and also /home/abc is present,

then you have to run the script like below:

$. a.sh abc

and it will go to /home/abc

Forever Learner
  • 1,465
  • 4
  • 15
  • 30