ksh 脚本 +在 shell 脚本中打印参数内容
我想用一个参数运行 script.sh
。
如果第一个参数 = 操作,则 script.sh
将打印操作参数 - 每 1 分钟重新启动一次机器
我的示例不起作用,但请建议脚本中需要修复哪些内容,以便如果参数是 action
,我将打印 $action
参数。
备注我不想设置以下解决方案 - [[ $1 = action ]] && echo 操作“每 1 分钟重新启动计算机
我的示例脚本:
#!/bin/ksh
action="restart machine each 1 min"
echo "action" ${$1}
如何运行脚本的示例
./script.sh action
我需要获得的预期结果:
action restart machine each 1 min
I want to run the script.sh
with one argument.
If the first argument = action then script.sh
will print the action parameter - restart machine each 1 min
My example not work but please advice what need to fix in the script so I will print the $action
parameter if argument is action
.
Remark I not want to set the following solution - [[ $1 = action ]] && echo action "restart machine each 1 min
My example script:
#!/bin/ksh
action="restart machine each 1 min"
echo "action" ${$1}
Example how to run the script
./script.sh action
Expected results that I need to get :
action restart machine each 1 min
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(3)
您想使用 eval:
action="restart machine each 1 min" eval echo $1 \$1
请注意,这样做会带来巨大的安全风险。考虑一下如果用户使用第一个参数“; rm -rf /”调用脚本会发生什么
您可能可以通过以下方式缓解此类问题:
eval "echo '$1' \"\$1\""
但实际上您只是自找麻烦(如果第一个参数包含双精度数,则最后一个版本将陷入困境-quote 和 $() 构造将允许执行任意命令)。简单地使用 case 语句并检查参数是否与您正在查找的字符串完全匹配会更安全。或者,至少检查您正在评估的参数是否不包含以下任何字符:;()$"'
。检查它是否仅包含字母数字 (a-zA-Z0-9
)
已经过去两年了,但这里有一个使用 nameref
(又名 typeset -N
)的示例。
它包括对给定论点有效性的三个连续测试。
- 是否给出论证?
- 参数与已知变量匹配吗?
nameref
检查这一点。 - 目标变量是否已设置值?
action='This is the value of $action'
word='This it the value of ${word}'
list='This is a list'
lie='This is a lie'
(
typeset name=${1:?Usage: script.sh varname} || exit
nameref arg1=${name} || exit
: ${arg1:?} || exit
echo "$name $arg1"
)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
好的,使用
pdksh
可以实现:Well with
pdksh
this works: