-1

I've tried the following ways to assign s value to a variable and print it:

user@ubuntu:~$ bash -c "variable=1111; echo $variable"

user@ubuntu:~$ bash -c "variable=1111; echo $variable > output"
user@ubuntu:~$ cat output

user@ubuntu:~$ bash -c "variable=1111 && echo $variable"

user@ubuntu:~$ bash -c "variable=1111 && echo $variable > output"
user@ubuntu:~$ cat output

user@ubuntu:~$

But as you see, in all the situations I failed to print 1111 in the output. What's wrong?

Ebrahim Ghasemi
  • 5,850
  • 10
  • 52
  • 113

1 Answers1

1

Simply: Use single quotes.

bash -c 'variable=1111; echo $variable'

The quotes are meaningful to the shell. Double quotes escape spaces and globs (roughly speaking, * expansion). but still allow for string interpolation. Single quotes do the same as double quotes, but they also escape the $.

Mark
  • 4,249
  • 1
  • 18
  • 27
  • Thank you. What does "escape" means here? It means "translate" or "leave it as it is"? – Ebrahim Ghasemi Mar 22 '20 at 15:29
  • 1
    Escape means leave it as it is. The idea is to pass the literal `$variable` to the bash executable. If you don't escapee it, the current shell will replace the `$variable` with a nothing and pass `variable=1111; echo` to the bash program. Another way of writing this code is to explicitly escape the `$` like this: `bash -c "variable=1111; echo \$variable"` – Mark Mar 22 '20 at 15:34