Thursday, 19 April 2018

How to preserve trailing whitespace in bash function arguments?




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?


Answer






  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"
    }



No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...