【问题标题】:Pass hash-sign-starting-string parameter to a shell script将 hash-sign-starting-string 参数传递给 shell 脚本
【发布时间】:2018-08-24 09:55:16
【问题描述】:

我尝试将包含在两个 # 符号之间的字符串传递给 ksh 脚本:

Will #> ./a.ksh #This is a string#

Will #>

没有提示,执行的输出将是:

Will #> ./a.ksh #This is a string#
#This is a string#

a.ksh 脚本下方。

a.ksh

echo $1
echo "$1"
echo ${1}
echo "${1}"

我试图以任何我知道的方式保护我的 $1 变量,但我 无法显示以# 开头的任何内容。

以下这些不起作用:

#> ./a.ksh #Hello
#> ./a.ksh #

但是这样做:

#> ./a.ksh Hello#

任何 shell 大师可以解释我为什么以及如何让它像 excpeted 一样工作?

我可以使用\#This String#"#This String#" 转义这些字符串,但我想知道为什么# 不能自行打印。

【问题讨论】:

    标签: linux shell parameters scripting ksh


    【解决方案1】:

    # 被解释为评论的开始。解释器会忽略所有 cmets。

    你有两个选择:

    1. 引用字符串使其成为文字:

      ./a.ksh "#This is a string#"

    2. 让您的脚本从用户那里读取输入而不是参数:

    这是一个例子:

    #!/bin/ksh
    echo "Enter your text:"
    read -r input
    echo "You entered: $input"
    

    然后先运行程序,然后输入你的数据:

    $ ./a.ksh
    Enter your text:
    #This is a string#
    You entered: #This is a string#
    

    【讨论】:

    • 关于小警告。 # 本身不会开始评论。考虑echo foo#bar。注释由以 # 开头的标记开始。
    • 太明显了,我错过了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-30
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多