1

I am to write a subscript (called echomyvar) that displays the PID of the process running the script and the value of the variable named myvar. In the text it has:

$ cat echomyvar
echo The PID of this process is $$
echo The value of myvar is: $myvar

$ echo $$
2651

$ ./echomyvar
The PID of this process is 4392
The value of myvar is:

I was able to create the file echomyvar. So far I have

#!/bin/bash
echo  'The PID of this process is $$'
echo  'The Value of myar is: $myvar'

I do not know if that is even correct. I am supposed to reproduce what was in the text.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232
  • Is this homework? You need to use double quotes (") for variables to be expanded. $$ contains the PID of the shell/script itself. – sebasth Sep 03 '17 at 22:57
  • 1
    Use enclosed by double quotes echo ''The Value of myar is: $myvar''. It will work. – Pandu Sep 04 '17 at 05:56

1 Answers1

3

The text that you quote,

echo The PID of this process is $$
echo The value of myvar is: $myvar

is the literal script that outputs the value of $$ (the process ID of the shell) and $myvar.

It will produce the output

The PID of this process is 4392
The value of myvar is:

(if the shell's PID happens to be 4392 that is).

It's not an exercise, it's an example, unless you are supposed to produce that script as output, but I doubt it.

The echo utility outputs each of its arguments to standard output (the terminal in this case). One usually use it like

echo 'some string'

or

echo "some string with a $variable"

Using single quotes in the last example would have prevented the shell from expanding $variable to its value. Using no quotes just means passing multiple arguments to echo.


For it to be a good example, it should have used printf (since it's outputting variable data):

printf 'The PID of this process is %d\n' "$$"
printf 'The value of myvar is: %s\n' "$myvar"

Related:

Kusalananda
  • 333,661