如何在bash函数参数中保留尾随空格?

mae*_*ics 5 bash whitespace function

请考虑以下bash脚本:

#!/bin/bash

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

foo 'Testing... ' 'OK' # => Testing...OK
# Whitespace --^                      ^
# Missing whitespace -----------------^
Run Code Online (Sandbox Code Playgroud)

第一个参数中的尾随空格发生了什么?怎么能保存它?

Car*_*rum 8

  1. 第一个参数中的尾随空格发生了什么?

    空格包含在echo命令行中,但被shell丢弃,就像你输入的一样:

    echo -n Testing... 
                      ^
                      |----- there is a space here
    
    Run Code Online (Sandbox Code Playgroud)
  2. 怎么能保存它?

    引用你的变量:

    function foo {
      echo -n "$1"
      echo "$2"
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 现在,我看到它是如此明显.我觉得很傻= D. (3认同)