0

I have seen many answers for this question but none is working right now.

Right now, I'm learning bash scripting, but whenever I write a shell script, I have to manually go and change its permission to executable before I can try it.

I have to use something like

chmod 755 <script.sh>

everytime I create a new script.

I have tried applying

chmod g+rwxs <directory>

on the parent directory, but it isn't working. Any Solutions?

I do not want the solution to be umask as I want it just for this directory and not for process of creating a new file as in whole.

2 Answers 2

1

First, IMHO, the permission system is there for your protection and it's best to learn to like. If, however, you really want to defeat it, here's how. Open some terminal and run the command:

inotifywait -m "$HOME/bin" -e close_write -e moved_to --format '%w%f' | while read -r fname; do chmod +x "$fname"; done

Or, for those who prefer their commands spread over multiple lines:

inotifywait -m "$HOME/bin" -e close_write -e moved_to --format '%w%f' |
   while read -r fname
   do
       chmod +x "$fname"
   done

This command will add execute permission to every file created in or moved to your $HOME/bin directory (or whatever other directory you choose).

If your system doesn't already have inotifywait installed, you may need to install it with a command like:

apt-get install inotify-tools

How it works

  • inotifywait -m "$HOME/bin" -e close_write -e moved_to --format '%w%f'

    This command watches the directory $HOME/bin. Any time a file is moved into that directory (moved_to) or written and closed in that directory (close_write), the command writes the files path and name to stdout.

    (A weakness here is that inotifywait doesn't support NUL-separated output. Consequently, this script won't work if your file name contains newlines.)

  • |

    This causes a pipeline to be started which sends the stdout of inotifywait to the next command's stdin.

  • while read -r fname; do

    This starts a loop which reads lines from stdin and assigns them to the variable fname.

  • chmod +x "$fname"

    This adds the execute bit to the file $fname. If you want other users on your system to be able to run commands, you may change this to chmod a+x "$fname". Or, you can change this to chmod 755 "$fname" if you really want to.

  • done

    This signals the end of the loop.

1

You can execute the script by using

bash <the script> <args> <to> <the> <script>

or even if you are already running bash and don't mind lingering variables:

. <the script> <args> <to> <the> <script>`

(because bash itself doesn't care about the execution flag, which is only checked by the same loader that looks at the "shebang" to determine how the script should be run).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .