Re: bash help

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



On 19Feb2017 05:22, Mike Wright <nobody@xxxxxxxxxxxxxxxxxxxx> 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 <cs@xxxxxxxxxx>
_______________________________________________
users mailing list -- users@xxxxxxxxxxxxxxxxxxxxxxx
To unsubscribe send an email to users-leave@xxxxxxxxxxxxxxxxxxxxxxx



[Index of Archives]     [Older Fedora Users]     [Fedora Announce]     [Fedora Package Announce]     [EPEL Announce]     [EPEL Devel]     [Fedora Magazine]     [Fedora Summer Coding]     [Fedora Laptop]     [Fedora Cloud]     [Fedora Advisory Board]     [Fedora Education]     [Fedora Security]     [Fedora Scitech]     [Fedora Robotics]     [Fedora Infrastructure]     [Fedora Websites]     [Anaconda Devel]     [Fedora Devel Java]     [Fedora Desktop]     [Fedora Fonts]     [Fedora Marketing]     [Fedora Management Tools]     [Fedora Mentors]     [Fedora Package Review]     [Fedora R Devel]     [Fedora PHP Devel]     [Kickstart]     [Fedora Music]     [Fedora Packaging]     [Fedora SELinux]     [Fedora Legal]     [Fedora Kernel]     [Fedora OCaml]     [Coolkey]     [Virtualization Tools]     [ET Management Tools]     [Yum Users]     [Yosemite News]     [Gnome Users]     [KDE Users]     [Fedora Art]     [Fedora Docs]     [Fedora Sparc]     [Libvirt Users]     [Fedora ARM]

  Powered by Linux