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 Answers1

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.

terdon
  • 242,166
  • +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 '22 at 04:16