简体   繁体   中英

How do I load a list from inside a file in bash?

I'm new to bash and I just want to load a list from a file mentioning that all the lines starting with # or ; should be ignored (and also empty ones).

As expected each valid line should became a string in the list.

I need to perform some action with each (valid) element of this list.

Note: I have a for loop like for host in host1 host2 host3 .

You can use bash builtin command mapfile to read file to an array:

# read file(hosts.txt) to array(hosts)
mapfile -t hosts < <(grep '^[^#;]' hosts.txt)

# loop through array(hosts)
for host in "${hosts[@]}"
do
    echo "$host"
done
$ cat file.txt 
this is line 1

this is line 2

this is line 3

#this is a comment



#!/bin/bash

while read line
do
    if ! [[ "$line" =~ ^# ]]
    then
        if [ -n "$line" ]
        then
            a=( "${a[@]}" "$line" )
        fi
    fi
done < file.txt

for i in "${a[@]}"
do
    echo $i
done

outputs:

this is line 1
this is line 2
this is line 3

If you aren't worried about spaces in the input, you can simply use

for host in $( grep '^[^#;]' hosts.txt ); do
    # Do something with $host
done

but the use of arrays and ${array[@]} in the other answers is safer in general.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM