0

I have a simple bash script to print the first argument provided to it

#!/bin/bash
echo $1

When I run this script as ./filename.sh $PATH it prints out all the content in the variable PATH. I just want it to display the "$PATH" string.

I have tried echo "$1" but it too behaves the same way.

Is there a workaround for this?

1
  • 2
    The shell is expanding the PATH variable, not your program. Call it as ./filename.sh '$PATH' Feb 19, 2022 at 12:43

1 Answer 1

5

No. There is no workaround because the variable is expanded by the shell before your script is launched, so your script never sees the variable, only the variable's contents.

However, there is a simple solution: variables are not expanded inside single quotes, so if you want to pass the variable as a string, and not as its value, just quote it:

$ ./filename.sh '$PATH'
$PATH

Make sure, however, to also quote the variable inside your script:

#!/bin/bash
echo "$1"

This won't make any difference in this particular case, but it is good practice and a good habit to develop.

1
  • +1. Escaping the $ with a backslash also works. ./filename.sh \$PATH. Either method prevents the shell you run ./filename.sh in from expanding the variable - they both cause it to treat $PATH as a literal string rather than a variable to be expanded.
    – cas
    Feb 20, 2022 at 4:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .