Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preserve trailing whitespace in bash function arguments? [duplicate]

Consider the following bash script:

#!/bin/bash

function foo {
  echo -n $1
  echo $2
}

foo 'Testing... ' 'OK' # => Testing...OK
# Whitespace --^                      ^
# Missing whitespace -----------------^

What happened to the trailing whitespace in the first argument? How can preserve it?

like image 724
maerics Avatar asked Feb 21 '13 22:02

maerics


1 Answers

  1. What happened to the trailing whitespace in the first argument?

    The whitespace was included on the echo command line, but was discarded by the shell, the same as if you had typed:

    echo -n Testing... 
                      ^
                      |----- there is a space here
    
  2. How can preserve it?

    Quote your variables:

    function foo {
      echo -n "$1"
      echo "$2"
    }
    
like image 93
Carl Norum Avatar answered Nov 09 '22 17:11

Carl Norum