On 19Feb2017 05:22, Mike Wright <nob...@nospam.hostisimo.com> wrote:
My brain cell ran away from home. I have an incredibly simple script that doesn't do what I expect. I use "mkdir DIR; cd DIR" a lot so I'm trying to put it in a script: "~/bin/mdcd".

After checking that $1 exists:

dir="$1"
mkdir -p "$dir"
cd "$dir"   <------ never executes

The directory is created so there is no error there.

Huh? Insight anyone?

Run you script with -x:

 sh -x your-script.sh args...

My suspicion is that your script work.

_However_, "cd" is a shell builtin because it affects the _current_ process. If you cd inside a shell script it moves the process running the shell script, _not_ your parent shell that invoked the script.

If you want a shell convenience to make a directory an cd into it you need a shell function: effectively a piece of script that runs in you current shell instead of as a subprocess.

For example, I have a 'cdf" function defined like this:

 cdf(){
   [ $# = 1 ] || { echo "Usage: cdf dir" >&2; return 2; }
   needdir "$1" && cd "$1" && pwd && { prepdir; L; }
 }

For context, "needdir" is a personal script that effectively does what your "mkdir -p" does, except that it checks first and tells me if it needed to make the directory; "prepdir" is a personal shell function that is intended to do some personal setup (but presently does nothing:-); "L" is a personal shell alias for "ls -la".

One important thing to note when writing shell functions: you can leave a shell function early (and set its "exit status") with "return". This is like "exit", but it terminates the shell function, not your shell!

Cheers,
Cameron Simpson <c...@zip.com.au>
_______________________________________________
users mailing list -- users@lists.fedoraproject.org
To unsubscribe send an email to users-le...@lists.fedoraproject.org

Reply via email to