[Discuss] How to keep '-' in bash args
pw
p.willis at telus.net
Tue May 1 12:08:44 PDT 2007
noel at natnix.com wrote:
> 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
This works but I have to put all my args into a single string:
#!/bin/bash
#test3.sh
for ARG in $1;do
FLAG=`printf '%s\n' "$ARG" |sed -e "s/\ //g" | \
awk '{A=index($0,"-");if(A==1){print 1}else{print 0 " " $0}}'`;
if [ "$FLAG" = "1" ]; then
echo "$ARG flag";
else
echo "$ARG not flag";
fi
done
run:
sh test3.sh "-flag1 value1 -flag2 value2 -flagn valuen"
output:
-flag1 flag
value1 not flag
-flag2 flag
value2 not flag
-flagn flag
valuen not flag
Peter
More information about the Discuss
mailing list