当前位置: 动力学知识库 > 问答 > 编程问答 >

bash - Need to check that my current directory is in a certain sub-directory

问题描述:

I am writing a script to help me organize my classes.

I want to be able to run a command such as

class econ -h

to go to the directory for my econ class, then to the sub-directory for homework (which is already created inside each class directory). I have that working perfectly, but I want to expand my program to allow simply:

class -h

from /home/USER/School/Semester-Fall/Econ/, what would I need to do to check that path and compare it to a default of let's say: /home/USER/School/Semester-Fall/

Please let me know if I wasn't clear enough or you need more information, thanks.

网友答案:

"Need to check that my current directory is in a certain sub-directory"

For convenience, let's define the "certain subdirectory" as default:

default="/home/USER/School/Semester-Fall/"

Now, to check to see if the current directory is under the directory defined by $default, use:

[ "${PWD#$default}" != "$PWD" ] && echo "Yes, we are under default"

or:

if [ "${PWD#$default}" != "$PWD" ]
then
    echo "Yes, we are under default"
else
    echo "No, we are not"
fi

Under bash, $PWD is the current working directory.

${PWD#$default} is an example of prefix removal. If the current working directory starts with the value of $default, then $default is removed.

If it is true that "${PWD#$default}" != "$PWD", then we know that $PWD starts with $default and, therefore, that the current working directory is under $default.

For this to work reliably, $default should end with a /.

Examples illustrating prefix removal

$ s=/home/USER/School/Semester-Fall/Econ/
$ echo "${s#/ho}"
me/USER/School/Semester-Fall/Econ/
$ echo "${s#/home/USER/School/Semester-Fall/}"
Econ/
$ echo "${s#/home/OtherUser/School/Semester-Fall/}"
/home/USER/School/Semester-Fall/Econ/
分享给朋友:
您可能感兴趣的文章:
随机阅读: