[Discuss] How to keep '-' in bash args

noel at natnix.com noel at natnix.com
Tue May 1 10:48:56 PDT 2007


if $1 is set to "-myarg", then 

	echo "$1"

expands to 

	echo -myarg

and echo will attempt to interpret "-myarg" as an option, instead of
printing it.

This problem is quite fun when you try to remove a file named "-".

Most commands accept "--" to signal the end of options, so this would
work for you:

	echo -- "$1"

But hold on!  echo does not support a "--" argument!  (I guess it does pay to
try your own advice before shooting your mouth off.) "echo -- -a" prints
"-- -a".  but "echo -a" prints "".

You could do a hack like this:

	echo "" -a

which prints " -a", but that leading space is annoying.

This might be a little more bullet-proof:

	printf '%s\n' "$1"

--Noel





On Tue, May 01, 2007 at 09:48:01AM -0700, pw wrote:
> Hello,
> 
> Can anyone tell me how to ensure (sh flags ??) that
> bash doesn't strip '-' from the front end of
> arguments passed to a shell script?
> 
> ie: sh script.sh  -myarg
> 
> #!/bin/bash
> #script.sh
> echo "$1"
> 
> 
> returns:
> myarg instead of -myarg
>                  ^
> 
> 
> Peter
> 
> _______________________________________________
> Discuss mailing list
> Discuss at vlug.org
> http://ladybug.vlug.org/cgi-bin/mailman/listinfo/discuss


More information about the Discuss mailing list