简体   繁体   中英

Linux alias with checking directory

How can I do alias which check if I'm in directory "python27" and when not it will be go to that directory, run some script and come back to home directory? When I'm in "python27" directory it should just run script and come back to home directory. I mean something like this:

alias p="if [ pwd != /home/myname ] then cd python27 && python $1 && cd ~ else python $1 && cd ~ fi"

Don't use an alias, use a function instead.

You don't need to check whether you're in the python27 directory, just cd there, run the script, and cd back home.

Something like this, with minimal checking:

p() {
    if [[ -z $1 ]]; then
        echo >&2 "need an argument"
        return 1
    fi
    if ! cd /full/path/to/python27; then
        echo >&2 "can't cd to python27"
        return 1
    fi
    python "$1"
    cd ~
}

You could also use python "$@" instead of python "$1" in case you need to pass more arguments (eg, options).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM