简体   繁体   English

带转义的Shell脚本变量扩展

[英]Shell script variable expansion with escape

The following script: 以下脚本:

#!/bin/bash

nested_func() {
    echo $1
    echo $2
}

func() {
    echo $1
    nested_func $2
}

func 1 "2 '3.1 3.2'"

Outputs: 输出:

1
2
'3.1

What I would like to get as output is: 我想得到的输出是:

1
2
3.1 3.2

How do I achieve this output with a single parameter on func instead of many? 如何在func上使用单个参数而不是多个参数来实现此输出?

EDIT made to address simplifications 编辑以解决简化问题

You can try this: 您可以尝试以下方法:

#!/bin/bash

nested_func() {
    echo "$1"
    echo "$2"
}

func() {
    nested_func "$@"
}

func 1 '2.1 2.2'

$@ represent all positional parameters given to the function $@表示赋予函数的所有位置参数


As an alternative you can use this: 或者,您可以使用以下方法:

#!/bin/bash

nested_func() {
    echo "$1"
    echo "$2"
}

func() {
    echo "$1"
    shift
    nested_func "$@"
}

func 1 2 '3.1 3.2'

The shift keyword allows to skip the first parameter. shift关键字允许跳过第一个参数。

You can easily map this if you have 4 parameters... 如果您有4个参数,则可以轻松地对此进行映射...

I have the expected output with this: 我对此有预期的输出:

#!/bin/bash
nested_func() {
    echo $1
    echo $2
}

func() {
    echo $1
    nested_func ${2%% *} "${2#* }"
}

func 1 "2 3.1 3.2"

Using Parameter expansion 使用参数扩展

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM