2

I have this line in my code:

    output=$(sed 's/\/$//g' <<< $output)

It works in #!/bin/bash but not in #!/bin/sh. In sh program exits with Syntax error: redirection unexpected, and after dissecting the error line, I've come to the conclusion that <<< is the problematic part. Also, in vim, vim grays out code below <<<, as if it is in some string. I'm just wondering why is this happening. Thanks in advance

  • 2
    <<< is a bash/ksh/zsh feature not present in sh. – glenn jackman May 5 '20 at 20:07
4

Yes <<< is a zsh operator now also supported by a few other shells (including bash), but it still hasn't been added in the standard specification of the sh language and a few sh implementations still don't support it.

To remove a trailing / from the contents of a variable it's just:

output=${output%/}

If instead you wanted to remove / from the end of every line in $output like that zsh code does, you could do:

output=$(printf '%s\n' "$output" | sed 's|/$||')

Or using the standard here-doc instead of zsh's here-string:

output=$(
  sed 's|/$||' << EOF
$output
EOF
)

Shells that support <<< are:

  • zsh, since 1991
  • Byron Rakitzis's clone of rc for Unix (though doesn't add an extra newline), since 1991 as well, and derivatives (es, akanga)
  • ksh93, since 2002
  • bash, since 2002
  • mksh, since 2008
  • yash, since 2009 (not when called as sh)

sh implementations that don't support it as of May 2020 include the Bourne shell, ksh88, ash and its derivatives (dash, the sh of busybox, FreeBSD, NetBSD), pdksh, posh, OpenBSD sh, bosh.

  • Wow great answer, thanks. Really helpful. – Fedja Mladenovic May 5 '20 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.