Puzzling behavior of YES command
This code ...
Code:
echo; echo "Case 1" Code:
Case 1 Case 2 produces an unexpected result, but didn't blow up. Case 3 blows up. Please advise. Daniel B. Martin |
In case 1, the first (and only) argument starts with a blank, and so it is treated as a simple text string. In cases 2 & 3, however, it starts with the hyphen, meaning that the command tries to treat it as an option flag.
The '--' in case 2 is treated as the "last option" option, clearing the way for the non-option arguments. But since there are no following arguments it uses the default 'y' In case 3 '- ' is simply an invalid argument. The way around it is to always use '--' first when the first non-option argument starts with a hyphen. Code:
yes -- '--' |head -n4 Edit: BTW, here's a quick&dirty way to get the same output using bash only. At least with low numbers of lines. Code:
printf '%s\n' '- '{,,,} |
Thank you, David the H., for this explanation.
A follow-on question... I was groping around hoping to find a Linux equivalent for the REXX built-in function COPIES, and thought yes would serve. As you explained, that works for many character strings but not all. This is how COPIES works: Code:
COPIES('FOO',3) returns 'FOOFOOFOO' (Without the quote marks) Daniel B. Martin |
Quote:
Code:
perl -e 'print "Foo"x3; print "\n"' |
Code:
bash-4.2$ copies() { for i in $(seq 1 "$2"); do printf "$1"; done } |
Slightly shorter printf solution:
Code:
printf "$s%.0s" $(seq 1 $n) |
Ruby is basically the same as perl in its format:
Code:
ruby -e 'puts "foo" * 3' Code:
awk 'BEGIN{OFS="foo";$3="foo";print}' |
Quote:
This code ... Code:
echo Code:
|
Quote:
In response to your question I coded those examples in a trivial REXX program. This code ... Code:
say COPIES('FOO',3) Code:
FOOFOOFOO Daniel B. Martin |
Sorry Daniel, I was unclear, I meant the dash examples in the original question, but as I said, I would guess it would not be affected as it is not a command with switches, which is why "yes" was affected.
|
(Inadvertent double post deleted.)
|
Quote:
Code:
say COPIES(' -',4) Code:
- - - - Daniel B. Martin |
Quote:
Daniel B. Martin |
> The way around it is to always use '--' first when the first non-option argument starts with a hyphen.
And when the argument is a parameter/variable: Code:
someprogram -- "$1" |
Well, if all you wanted was to duplicate a string 'n' times, you should've said so! ;)
Code:
$ printf -v string '%03d' ; echo "${string//0/foo}" Code:
#$1 is the string to copy |
All times are GMT -5. The time now is 09:20 AM. |