【问题标题】:How to read multiple words as one argument如何阅读多个单词作为一个参数
【发布时间】:2019-07-13 11:36:35
【问题描述】:

我正在尝试编写一个 shell 脚本,它将给它的第一个单词作为一个参数,并将它之后的任何内容作为第二个参数。

用户必须调用我的shell脚本并在终端的一行中提供他们的参数:shellscript.sh word1 word2 word3 ...... wordn 我怎样才能写出这样的脚本

arg1 = word1

arg2 = word2 - wordn?

【问题讨论】:

  • 这可能会有所帮助:help shift
  • 我建议让调用者负责构造第二个参数:shellscript.sh word1 "word2 word3 ..."

标签: bash shell unix terminal arguments


【解决方案1】:

使用shift 删除第一个参数,使用"$*" 连接其余参数。

#!/bin/bash
first=$1
shift
rest="$*"  # Assuming the first character of $IFS is a space.

printf '<%s>\n' "$first" "$rest"

【讨论】:

  • 请注意,您正在全局更改IFS;赋值本身不带前置命令修饰符。
  • @chepner:谢谢,已修复。
猜你喜欢
  • 1970-01-01
  • 2020-07-20
  • 2019-09-04
  • 2020-07-17
  • 1970-01-01
  • 2019-11-05
  • 1970-01-01
  • 2012-03-15
  • 1970-01-01
相关资源
最近更新 更多