henry
henry

Reputation: 4385

How to echo bare hypen (`-`) in zsh?

I'm looking for a way to work around zsh echo's apparently treating a string that is just a hyphen as if it were an empty string

echo -
# no output

echo "-"
# no output

echo '-'
# no output

Specifically, I'm splitting a string at a known character and then working with the two pieces, and either of the two pieces could be -. Like

% my_f() {
  my_arr=(${(s.b.)1})
  echo $my_arr[1]
  echo $my_arr[2]
}

% my_f "abc"
a
b

% my_f "-bc"
# I need to know -
b

% my_f "ab-"
a
# I need to know -

%

In the particular thing I'm working on, I can rework things so that the potential - isn't echo'd on its own

my_arr=(${(qqqs.b.)1})
echo " ${(Q)my_arr[1]} "
echo " ${(Q)my_arr[2]} "

But that feels like luck and will take sprinkling a lot of qqq and Q around this script. Is there a better way?

Upvotes: 0

Views: 60

Answers (2)

chepner
chepner

Reputation: 531798

Use printf instead. (Which is generally good advice regarding any use of echo.)

my_f () {
  printf '%s\n' "${(s.b.)1}"
}

Upvotes: 1

evnp
evnp

Reputation: 301

Try echo - "-". The first dash terminates option processing, so following text is printed.

See this excellent answer for more context: https://stackoverflow.com/a/57656708/11776945

Upvotes: 1

Related Questions