I have two very simple scripts, differing only by the presence of a blank first line:
$ cat test.bash
#!/bin/bash
echo ${UID}
$ cat test_blank.bash
#!/bin/bash
echo ${UID}
Now I run then, with and without nice
:
$ ./test.bash
1060
$ ./test_blank.bash
1060
$ nice ./test.bash
1060
$ nice ./test_blank.bash
Please explain why, in the final case, the UID
variable is unset. The behavior is the same when replacing nice
with sudo
or nohup
.
Adding #!/bin/bash as the first line of your script, tells the OS to invoke the specified shell to execute the commands that follow in the script. #! is often referred to as a “hash-bang”, “she-bang” or “sha-bang”. Though it is only executed if you run your script as an executable.
bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.
$_ (dollar underscore) is another special bash parameter and used to reference the absolute file name of the shell or bash script which is being executed as specified in the argument list. This bash parameter is also used to hold the name of mail file while checking emails.
bashrc. This internal variable controls character interpretation in globbing and pattern matching.
Observe:
$ bash test_blank.bash
1060
$ dash test_blank.bash
bash
produces output but dash
, which is the default sh
on debian-like systems, does not. This is because bash
sets UID
but dash does not. (POSIX does not require a shell to set UID
.) So, the question becomes which shell executes the script.
When bash sees ./test.sh
, it (bash) runs the script. When another command, such as nice
, receives the script as an argument and the script does not have a valid shebang as the first line, then the default shell, likely dash
, is run.
If you want UID in dash, or any other shell that does not provide it, use the id
command:
UID=$(id -u)
To see which shell is running a script, use:
$ cat test2.sh
#!/bin/bash
ps $$
echo UID=${UID}
Under bash
:
$ ./test2.sh
PID TTY STAT TIME COMMAND
1652 pts/12 S+ 0:00 bash -rcfile .bashrc
UID=1060
If we invoke it using nice
, by contrast, we can see that it is running under /bin/sh
and the UID variable is not assigned:
$ nice test2.sh
PID TTY STAT TIME COMMAND
1659 pts/12 SN+ 0:00 /bin/sh test2.sh
UID=
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With