以相反的顺序打印 shell 参数

War*_*ith 13 bash parameter shell-script

我有点卡住了。我的任务是将参数以相反的顺序打印到我的脚本中,除了第三个和第四个。

我有的是这个代码:

#!/bin/bash

i=$#
for arg in "$@"
do
    case $i
    in
        3) ;;
        4) ;;
        *) eval echo "$i. Parameter: \$$i";;
    esac
    i=`expr $i - 1`
done
Run Code Online (Sandbox Code Playgroud)

由于我讨厌 eval(向 PHP 致意),我正在寻找没有它的解决方案,但我找不到。

如何动态定义参数的位置?

PS:不,这不是作业,我正在为考试学习 shell,所以我尝试解决旧考试。

Gil*_*il' 14

eval是通过动态选择的位置访问位置参数的唯一可移植方式。如果您显式循环索引而不是值(您没有使用),您的脚本会更清晰。请注意,expr除非您希望您的脚本在古董 Bourne shell 中运行,否则您不需要;$((…))算术在 POSIX 中。将使用限制为eval尽可能小的片段;例如,不要使用eval echo,将值分配给临时变量。

i=$#
while [ "$i" -gt 0 ]; do
  if [ "$i" -ne 3 ] && [ "$i" -ne 2 ]; then
    eval "value=\${$i}"
    echo "Parameter $i is $value"
  fi
  i=$((i-1))
done
Run Code Online (Sandbox Code Playgroud)

在 bash 中,您可以使用${!i}来表示名称为 的参数的值$i。这适用于$i命名参数或数字(表示位置参数)。在此过程中,您可以使用其他 bash 便利功能。

for ((i=$#; i>0; i--)); do
  if ((i != 3 && i != 4)); then
    echo "Parameter $i is ${!i}"
  fi
done
Run Code Online (Sandbox Code Playgroud)


小智 7

reverse在我的路径上保留了一个脚本来执行此操作:

#!/bin/sh

if [ "$#" -gt 0 ]; then
    arg=$1
    shift
    reverse "$@"
    printf '%s\n' "$arg"
fi
Run Code Online (Sandbox Code Playgroud)

用法示例:

$ reverse a b c '*' '-n'
-n
*
c
b
a
Run Code Online (Sandbox Code Playgroud)

您还可以使用函数而不是专用脚本。

  • @G-Man,在列表上下文中未加引号的变量正在调用 split+glob 运算符。你没有理由想在这里调用它。这与变量的内容无关。另见 http://unix.stackexchange.com/a/171347 最后。另请注意,某些 shell(例如 dash、posh)仍然从环境中继承 IFS。 (2认同)