开发者

How to make a BASH script work only in a specific directory?

my Linux homework requires that I write a script that only runs if the user is in ~/tareas/sesion_3, so I assume he first needs to input cd /~/tareas/sesion_3 and then the script commands will run, if not it'll echo "you're not on /~/tareas/sesion_3". In the script I need to make more directories, and they can only be created in that location.

How can I make such condition?

I appreciate ever开发者_JS百科y bit of help you guys can offer!


You can use $PWD to see what parent directory the script was run from, although it will have expanded ~ already. So you can do something like:

if [[ "$PWD" == "/home/tareas/session_3" ]]; then
  # do stuff if true
else
  # do stuff if false
fi


my answer is:

#!/bin/sh

TARGET_DIR = "~/tareas/sesion_3" 

function do_something(){
    #do something
}

function do_something_v2(){
    #create some dirs
}

if [ `pwd` == "$TARGET_DIR" ] ; then
    do_something
else 
    do_something_v2

i hope it can help you

^_^


If you need to see if you are at least inside of the given directory, but perhaps in a child directory therein, grep is a good friend to have:

echo `pwd` | grep ^/starting/directory >/dev/null || {
       echo "You aren't in the proper place .."
       exit 1
}

Example of it working:

tpost@tpost-desktop:~$ echo `pwd` | grep ^/home/tpost >/dev/null || echo nope
tpost@tpost-desktop:~$ echo `pwd` | grep ^/home/foo >/dev/null || echo nope
nope

The carat (^) tells grep to match a line that starts with what you provide.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜