从变量中获取特定的第N个单词

时间:2018-04-10 16:37:47

标签: linux bash shell variables

我有这个脚本

#!/bin/bash

tmpvar="$*"
doit () {
    echo " ${tmpvar[1]} will be installed "
    apt-get install ${tmpvar[2*]}
    echo " ${tmpvar[1]} was installed "
}
doit

哪个在命令./file.sh word1 word2 word3 word4下有效 重点是获得“回声”的第一个词。以及安装命令的其余部分。

示例:./file.sh App app app-gtk 因此,在“回声”中显示第一个单词。并获得apt命令的其余部分。 但这不起作用。

2 个答案:

答案 0 :(得分:1)

您可以在此处使用shift

doit () {
   arg1="$1"  # take first word into a var arg1
   shift      # remove first word from $@

   echo "$arg1 will be installed..."
   # attempt to call apt-get
   if apt-get install "$@"; then
      echo "$arg1 was installed"
   else
      echo "$arg1 couldn't be installed">&2
}

并将此函数称为:

doit "$@"

答案 1 :(得分:0)

file.sh看起来像

#!/bin/bash

doit () {
    local name=$1
    shift
    echo " $name will be installed "
    apt-get install "$@"
    [[ $? -eq 0 ]] && echo " $name was installed "
}

# pass all the parameters to the function
doit "$@"