进入for循环后获取变量的原始值

问题描述 投票:0回答:2

我正在制作一个简单的脚本,该脚本遍历当前目录中的文件,$1用于大小参数,其他$1,$2 .....用于操作文件并设置文件名。问题是使用for循环后,变量将丢失其值,并以1,2,3之类的整数开头,除非我使用名为1,2,3,...的文件,否则脚本将无法工作。如何保留原始值?例如: ./script 50 my_first_file .....

#!/bin/bash
size=$1
allfiles=$#
shift
#here the value of the $1 is "my_first_file"
  for ((i = 1 ; i < allfiles ; i++))
  do
  #here the value of the $1 = 1
  done
bash for-loop
2个回答
1
投票

而不是使用带有整数的for循环,您可以像这样直接在参数上循环:

#!/bin/bash

size="$1"
allfiles=$#
shift

counter=1
for i in "$@"
do
    echo "$counter= $i"
    (( counter = counter + 1 ))
done

echo "size= $size"

这将按顺序显示每个参数。如果需要显示或使用每个参数的位置,可以使用一个计数器。

如果我这样称呼:script.bash 25 a b c输出为:

1= a
2= b
3= c
size= 25

1
投票

另一种选择是简单地循环浏览文件。

#!/usr/bin/env bash

size=$1
shift

counter=1

for f; do
  printf '%d. %s\n' "$((counter++))" "$f"
done

printf 'size=%s\n' "$size"



© www.soinside.com 2019 - 2024. All rights reserved.