Answer to your question
Of course that’s possible – but I’d not consider it good style. See below for a better solution.
If you run a shell and give it the script file as an argument it will execute it regardless of the absence of a shebang or any execution bit:
$ cat no_script
chmod +x /path/to/no_script
$ ls -l no_script
-rw-rw-r-- 1 dessert dessert 24 Jun 12 22:59 script
$ bash no_script
$ ls -l no_script
-rwxrwxr-x 1 dessert dessert 24 Jun 12 22:59 script
If the script is executed multiple times you probably don’t want to call chmod
without any need every time, so just test for the file being not executable:
[ ! -x /path/to/script ] && chmod +x /path/to/script
As for your script, awk
can do the whole thing in a single call:
#!/bin/bash
tune2fs -l /dev/sda1 | awk '/^Block count:/{a=$NF}/^Reserved block count:/{b=$NF}END{printf "%.1f%%\n", b/a*100}'
I removed the sudo
because you don’t use it in a script – run the whole script as root instead.
Solution to your problem
I read from your question that you’re bothered by the two steps necessary to set up a script. Let’s write a script that helps with that:
#!/bin/bash
cat <&0 >"$1" &&
chmod +x "$1"
cat <&0 >"$1"
makes cat
read from stdin and write to the script file you give it as the first argument. Save this as e.g. makescript
and make it executable with chmod +x /path/to/makescript
. Now if you want to write a script, simply do it like that:
/path/to/makescript /path/to/new/script <<EOF … EOF
If you don’t want to type /path/to/makescript
every time, define an alias like makescript=/path/to/makescript
in your ~/.bash_aliases
or ~/.bashrc
or move it to a directory in your PATH
.
Example run
$ echo -e '#!/bin/bash\ncat <&0 >"$1" &&\nchmod +x "$1"' >makescript
$ chmod +x makescript
$ ./makescript a_test_script <<EOF
> #!/bin/bash
> echo a script
> EOF
$ ls -l *script
-rwxrwxr-x 1 dessert dessert 26 Jun 13 12:44 a_test_script
-rwxrwxr-x 1 dessert dessert 43 Jun 13 12:44 makescript
$ ./a_test_script
a script
The sky is the limit.