Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, double quotes and "reboot" command

Tags:

bash

Assume you have those two statements in your bash script:

# No. 1
MSG="Automatic reboot now."
echo $MSG

# No. 2
MSG=""Automatic reboot now.""
echo $MSG

The output of statement number 1 is as expected (it is simply printed). If bash runs statement two, the machine is rebooted (any valid bash command will be executed).

But why?

like image 383
Linuxfabrik Avatar asked Dec 21 '25 10:12

Linuxfabrik


2 Answers

That's because the meaning of MSG=""Automatic reboot now."" is the following:

Execute reboot now. with the env. var. MSG set to Automatic.

It's equivalent to:

MSG=Automatic reboot now.
like image 125
basin Avatar answered Dec 24 '25 02:12

basin


A lesser known shell feature is the ability to set environment variables for the duration of a single command. This is done by prepending a command with one or more assignments, as in: var1=foo var2=bar command.

Here's a demonstration. Notice how the original value of $MSG is preserved.

$ export MSG=Hello
$ bash -c 'echo $MSG'
Hello
$ MSG=Goodbye bash -c 'echo $MSG'
Goodbye
$ bash -c 'echo $MSG'
Hello

Now on to your question:

MSG=""Automatic reboot now.""

The pairs of double quotes nullify each other, and might as well not be there. It's equivalent to:

MSG=Automatic reboot now.

which executes reboot with an argument of now. and the $MSG environment variable set to Automatic.

like image 20
John Kugelman Avatar answered Dec 24 '25 01:12

John Kugelman