How to handle special characters in command line arguments for a shell script

Viewed 641

I have the following shell script where I just want to print out the first argument as it is passed in

Code:

#!/bin/bash

if [ "$1" == "" ]; then
    exit 1
fi

echo $1

Lets say name of the script is testarg.sh which is called as follows - testarg.sh abc. Great!

Above shell script works if I pass simple arguments like "abc" or "xyz123". And calling it like testarg.sh xyz123 prints out "xyz123". All good!

Problem:
But if does print the content accurately if I pass a complex string with special characters. Lets say I called it like this below:

./testarg.sh $6$nB3/jwAqgRcS9LN7$8c5InVbk5SLFiwuz9Xm6EHHRuZHMI0ggMhmxJ7Pr7NuBZ0TXtProuZ6LpQ6ZrFySly12cbGmWHsFpukEKAzdW.

Question:
In the above call I want to pass $6$nB3/jwAqgRcS9LN7$8c5InVbk5SLFiwuz9Xm6EHHRuZHMI0ggMhmxJ7Pr7NuBZ0TXtProuZ6LpQ6ZrFySly12cbGmWHsFpukEKAzdW. as the argument and print it out exactly as it is including the slash and dots. Do I need to apply special tricks?

I don't want the user of my script to bother inserting special escape characters for the slashes. Is there a way I can handle this nicely in my script and get the value of $1 as it is to print it out accurately?

1 Answers

You need to call the script with single quotes around the argument. There is no way to make this work by changing the code of the script.

./testarg.sh '$6$nB3/jwAqgRcS9LN7$8c5InVbk5SLFiwuz9Xm6EHHRuZHMI0ggMhmxJ7Pr7NuBZ0TXtProuZ6LpQ6ZrFySly12cbGmWHsFpukEKAzdW.'
Related