Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding !# and $@ in bash

I've just recently started programming scala, and in the book "Programming in Scala"(www.artima.com/pins1ed) the following method of executing scala scripts in linux is presented:

#!/bin/sh
exec scala "$0" "$@"
!#
// Say hello to the first argument
println("Hello, "+ args(0) +"!")

Now I've been using linux for a long time, but bash scripting is not my speciality. Now I can guess how this type of scrpt works(and it works beautifully), but I was wondering what do the !# and $@ do exactly.

Thanks in advance for all the help!

like image 623
Kapenaar Avatar asked Feb 22 '26 01:02

Kapenaar


2 Answers

Beautiful indeed. $0 and "$@" are positional paramters ($0 = command itself just like argv[0] in C, and argv[1]+ for "$@"), whereas #!* tells the shell, and sometimes the kernel if it recognizes it which program to execute for the file.

The thing that happens here actually is that the shell opens the script for input reading but on the point of exec, it transfers the input to scala, but scala wouldn't have to read it again from the beginning since the file descriptor is still open and so scala continues reading on the next line.

Rarely do I see scripts that do that with apparent and simple presentation of how it functions.

Note that exec replaces the process of the shell running the script and so it's like the shell becomes scala but scala would have the environment variable and opened handlers as the same.

UPDATE

Looks like I was wrong. Scala itself reads the whole but skips what it could see as header lines to it. So this is the real purpose of !#:

Script files may have an optional header that is ignored if present. There are two ways to format the header: either beginning with #! and ending with !#, or beginning with ::#! and ending with ::!#.

like image 141
konsolebox Avatar answered Feb 23 '26 21:02

konsolebox


!# doesn't have anything to do with Bash. It's part of the Scala Language. It separates a non-Scala header from Scala Code in Script Mode.

like image 29
Jörg W Mittag Avatar answered Feb 23 '26 21:02

Jörg W Mittag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!