Thursday, April 19, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...