English 中文(简体)
在bash中对列表中的选定元素应用操作
原标题:Apply actions over selected elements in a list in bash
  • 时间:2023-12-08 02:29:17
  •  标签:
  • bash

我有一个bash脚本,它有4个元素,我想循环最后2个元素。所以我试了一下:

#!/usr/bin/env bash
arg1=$1
arg2=$2
arg3=$3
arg4=$4
list_total=( "$3 $4" )

for my_element in "${list_total}"; do
    echo "$my_element"
    echo "Wow"
done

使用sh myscript.sh Joe Jack Jim Jess运行时,输出为:

Jim Jess
Wow

但这不是我对剧本的打算。我想输出:

Jim
Wow
Jess
Wow

拜托,你能指出我做错了什么吗?

最佳回答

您需要使用单独的元素而不是单个字符串创建LIST_TOTAL数组。为此,请将LIST_TOTAL = ("$ 3 $ 4")行更改为LIST_TOTAL = ("$ 3" "$ 4")。类似于:

#!/usr/bin/env bash
arg1=$1
arg2=$2
arg3=$3
arg4=$4
list_total=( "$3" "$4" ) # <--- Here

for my_element in "${list_total[@]}"; do
    echo "$my_element"
    echo "Wow"
done

如果您正在寻找此情况的替代方案:

外壳参数扩展

#!/usr/bin/env bash
# Directly access the script s arguments
for ((i = 3; i <= 4; i++)); do
  my_element="${!i}"
  echo "$my_element"
  echo "Wow"
done

示例演示

问题回答

另一个使用数组拼接的版本:

#!/usr/bin/env bash
list_total=$@
for my_element in ${list_total[@]:3:4}; do
    echo "$my_element"
    echo "Wow"
done




相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

Bash usage of vi or emacs

From a programming standpoint, when you set the bash shell to use vi or emacs via set -o vi or set -o emacs What is actually going on here? I ve been reading a book where it claims the bash shell ...

Dynamically building a command in bash

I am construcing a command in bash dynamically. This works fine: COMMAND="java myclass" ${COMMAND} Now I want to dynamically construct a command that redirectes the output: LOG=">> myfile.log ...

Perform OR on two hash outputs of sha1sum

I want perform sha1sum file1 and sha1sum file2 and perform bitwise OR operation with them using bash. Output should be printable i.e 53a23bc2e24d039 ... (160 bit) How can I do this? I know echo $(( ...

Set screen-title from shellscript

Is it possible to set the Screen Title using a shell script? I thought about something like sending the key commands ctrl+A shift-A Name enter I searched for about an hour on how to emulate ...

热门标签