0

I am writing a bash script and I want to prevent the user from running the script as

$ ./myscript.sh

and instead, run it as

$ . ./myscript.sh

Is this possible to be done in CentOS 7?

So my approach was to check for the first . and see if it exists. I tried the following. Seems like it is not printing the full string executed at the command line.

Content of myscript.sh

#!/bin/bash 
for i; do 
    echo $i 
done
Cyrus
  • 84,225
  • 14
  • 89
  • 153
afp_2008
  • 1,940
  • 1
  • 19
  • 46
  • 1
    The first `.` does not get passed to your script. It is used by the shell and your script will never see it. It isn't really clear what exactly you are trying to achieve. – kaylum Mar 22 '21 at 20:42
  • 3
    See: [How to detect if a script is being sourced](https://stackoverflow.com/q/2683279/3776858) – Cyrus Mar 22 '21 at 20:44
  • @Cyrus Why not vote to close as dup? – P.P Mar 22 '21 at 20:46
  • 1
    Silly question, but is there any functional difference between `./foo.sh` and `. ./foo.sh` or `sh foo.sh`? – Abelisto Mar 22 '21 at 20:50
  • 1
    @P.P: Perhaps someone has a suitable answer to the question in the heading. – Cyrus Mar 22 '21 at 20:50
  • 3
    @Abelisto: see: [What is the difference between sourcing ('.' or 'source') and executing a file in bash?](https://unix.stackexchange.com/q/43882/74329) – Cyrus Mar 22 '21 at 20:52
  • 1
    @Cyrus Yes. But it is related to parent process, not to the script itself. Lets say: if the script contains somthing like `rm -fr ~` result will be same. – Abelisto Mar 22 '21 at 20:59

0 Answers0