【问题标题】:KSH String formatting issueKSH 字符串格式问题
【发布时间】:2023-01-12 17:47:00
【问题描述】:

我在 KSH 脚本中有一个转换函数:

function convert_string_to_seconds
{
    # $1: time as a string e.g. 200s (for 200 seconds)
    # output: $time_in_seconds containing the input string converted into seconds
    
    typeset timeselector input numeral
    typeset -i in
    
    input=$1
    numeral=$(print ${input%?})
    timeselector=$(print ${input#${input%%?}})
    case $timeselector in
        ("s")
            time_in_seconds=$numeral
            break ;;
        ("m")
            time_in_seconds=$(( $numeral * 60 ))
            break ;;
        ("h")
            time_in_seconds=$(( $numeral * 3600 ))
            break ;;
        (*)
            exit 7
            ;;
    esac

}

该值来自配置文件,其中包含如下一行:

MAXRECOVERY=200s

捕获值的代码是:

value=$(echo $line | cut -d '=' -f 2)

如果我运行convert_string_to_seconds $value,那么input=200snumerals=200stimeselector="" 如果我运行convert_string_to_seconds 200s,那么input=200snumerals=200timeselector=s

如果我运行echo "|${value}|",我会得到|200s|,所以没有空格、\n 或类似的东西。

我错过了什么?

试过:

input=$1
input="$1"
input=$(printf '%s\n' "$1")
numeral=$(print ${value%?})
numeral=$(print ${value%?} | tr -d "\r")
timeselector=$(echo $value | sed 's/.*\(.\)/\1/')
timeselector=$(print ${value#${value%%?}} | tr -d "\r")

【问题讨论】:

    标签: scripting formatting ksh


    【解决方案1】:

    尽管有 echo "|"$input"|" 返回 |200s|,但看起来有一个 隐藏在我的输入中,所以用 input=$(echo $1 | tr -d " ") 替换 input=$1 解决了这个问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 2013-05-13
      • 2018-11-07
      • 2019-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多